Unit-2-Introduction To Python Programming
Unit-2-Introduction To Python Programming
Introduction
to
Python Programming
Program and Programming Language
An ordered set of instructions or commands executed by a computer is called program. The language used to
write these instructions is called programming language. For example, C, C++, Java, Python etc. Python is a
programming language created by GUido Van Rossum in 1991.
Translator
Translator is a software that converts the high level language program to machine language.
e
nc
Compiler and Interpreter
ie
Sc
Compiler:
A compiler converts the high level language program in machine language.
p.
om
1. Compiler translates the whole program at once.
2. Errors are shown after compilation.
3. Execution is faster.
rC
4. Example: C, C++
re
Interpreter:
tu
Interpreter also converts the high level language program in machine language but line by line.
ec
To write and run a Python program, we need to have a Python interpreter installed on our computer. The
es
interpreter is also called Python shell. The symbol >>> is called Python prompt which indicates that the
interpreter is ready to retrieve instructions.
ah
M
Execution Modes
There are two ways to run a program using python interpreter: a) Intractive mode b) Script mode
(A) Intractive mode
In this mode, we type a python statement on the >>> prompt. As soon as we press enter, the interpreter
executes the statement and display the result.
e
Disadvantage: We cannot save the statements for future use and we have to
nc
retype the statement to run them again.
ie
(B) Script mode
Sc
In this mode, we write a Python program in a file, save it and then use the interpreter to execute the program
p.
from the file.
om
Python IDLE(Integrated Development and Learning Environment) can be used to create program.
rC
re
tu
ec
|L
ar
hw
e
nc
1. Comments (optional)
ie
2. Import statements (optional)
Sc
3. Variable declarations
4. Function definitions (optional)
5. Main program code
p.
om
Example of Python Program Structure rC
In [2]: # This is a comment
import math # Importing a module
re
tu
a = 10 # Variable
b = 20
ec
def add(x, y): # Function definition
|L
return x + y
result = add(a, b) # Main code
ar
Sum = 30
es
For example:
and, or, break, continue, if, else, import, True, for, while
Identifiers
e
nc
Identifiers are the names to identify a variable, function or other entities in a program.
ie
The rules for naming an identifier in Python are as follows:
Sc
1. The name should begin with an uppercase or a lowercase alphabet or an undersco
re sign(_).
p.
2. It can be of any length.
om
3. It should not be a keyword or reserved word.
4. Special symbols like @, #, $, % etc. cannot be used.
rC
Identifier cannot start with a digit.
re
tu
ec
|L
ar
hw
es
ah
M
variables
Variables are identifiers whose value can change. For example,
In [3]: age=50
print("age: ",age)
age=70
print("age: ",age)
age: 50
age: 70
Variable names are case-sensitive.
a=4
A = "Sally"
Variables must always assigned values before using in prgram, otherwise it will lead to an error.
In [5]: marks
print("marks: ",marks)
---------------------------------------------------------------------------
e
NameError Traceback (most recent call last)
nc
<ipython-input-5-3a4e4b69dd54> in <module>()
----> 1 marks
ie
2 print("marks: ",marks)
Sc
NameError: name 'marks' is not defined
p.
om
Data Types rC
Data types identifies the type of data which a variable can hold.
re
tu
ec
|L
ar
hw
es
ah
1. Lists
2. Dictionaries
3. Sets
Immutable types
Immutable types are those that can never change their value in place. The following are the immutable
dayatypes:
1. integer
2. floating point numbers
3. Boolean
e
nc
ie
Sc
p.
om
rC
re
tu
ec
|L
ar
hw
es
ah
M
Operators in Python
An operator is used to perform specific mathematical or logical operation on values. The values that the
operator works on are called operands. For example,
In [1]: a=10
b=20
c=a+b #here, a and b are operands and + is an arithmetic operator.
print("c: ",c)
c: 30
e
nc
Types of operators ¶
ie
Sc
p.
om
rC
re
tu
ec
|L
ar
hw
es
ah
M
Examples
In [9]: p=51
q=4
r=p//q #arithmetic operator
print("r: ",r)
r: 12
In [5]: a=20 #Assignment operator
b=20
c=a==b #relational operator
print("c: ",c)
c: True
In [10]: a=10
b=20
c=30
result=a<b<=c
print("Result: ", result )
Result: True
e
nc
In [6]: a=10
b=0
ie
c= a and b #logical operator
Sc
print("c: ",c)
c: 0
p.
In [7]: L=[10,20,30,40]
om
c= 20 in L #membership operator
print("c: ",c)
rC
c: True
re
Result: 64.0
In [22]: a=2+-+-3
while a>2:
print(a)
break
e
nc
5
ie
In [23]: result= 4**2/4*(5+9)
Sc
print("Result: ",result)
Result: 56.0
p.
In [24]: result=16%4**3//5+8
om
print("Result: ",result)
Result: 11
rC
In [26]: a=50-10*3
re
b=(50-10)*3
print("Rule A: ", a)
tu
print("Rule B: ", b)
ec
Rule A: 20
Rule B: 120
|L
In [27]: result=(2-6+3**2*3)+7
ar
print("Result: ",result)
hw
Result: 30
es
In [28]: result=12.0/4+(9+1.0)
print("Result: ",result)
ah
Result: 13.0
M
In [12]: x,z=5,10
y=x+3
x=x-1
x=x+z
print('x:',x,'y:',y,'z:',z)
x: 14 y: 8 z: 10
In [15]: print(type(1+3))
print(type(1+3.0))
<class 'int'>
<class 'float'>
In [17]: print(type(11+3))
print(type('11'+3))
<class 'int'>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-17-c048cfe30a0e> in <module>()
e
1 print(type(11+3))
nc
----> 2 print(type('11'+3))
ie
TypeError: must be str, not int
Sc
Associativity of Operators in Python
p.
om
In Python, associativity determines the order in which operators with the same precedence are evaluated
when they appear in an expression.
rC
1. If two operators have the same precedence, the expression is evaluated from le
re
ft to right.
tu
3. The exponentiation (**), assignment (=, +=, etc.), logical NOT (not) operators
|L
In [18]: a=5-4-3
hw
b=3**2**3
print(a)
es
print(b)
-2
ah
6561
M
In [22]: x,y=4,8
z=x/y*y
print(z)
4.0
In [19]: a,b,c=1,1,2
d=a+b
e=1.0
f=1.0
g=2.0
h=e+f
print(c==d)
print(c is d)
print(g==h)
print(g is h)
True
True
True
e
False
nc
ie
Sc
p.
om
rC
re
tu
ec
|L
ar
hw
es
ah
M
Python Comments
1. Comments can be used to explain Python code.
e
Creating a Comment
nc
Comments starts with a ' # ', and Python will ignore them:
ie
Sc
In [1]: #This is a comment
print("Hello, World!")
p.
Hello, World!
om
A comment does not have to be text that explains the code, it can also be used to prevent Python from
rC
executing code:
re
Cheers, Mate!
ec
|L
You can add a multiline string (triple quotes(''' ''')) in your code, and place your comment inside it:
ar
In [3]: """
This is a comment
hw
written in
more than just one line
"""
es
print("Hello, World!")
ah
Hello, World!
M
Input in Python
The input() function is used to get data from the user via the keyboard.
Syntax:
variable = input("prompt_message")
Default Type:
The input() function always returns the user's input as a string by default, regardless of what is typed.
Type Conversion:
To work with other data types (like integers or floats), you must explicitly convert the input using typecasting
functions like int() or float().
e
In [8]: # Basic string input
nc
name = input("Enter your name: ")
print("Hello,", name) # Output: Hello, [user's name]
ie
# Integer input (with type conversion)
Sc
age_str = input("Enter your age: ")
age_int = int(age_str)
print("Next year you will be", age_int + 1)
p.
Enter your name: Maheshwar
om
Hello, Maheshwar
Enter your age: 36
rC
Next year you will be 37
re
Output in Python
tu
Syntax:
print(value(s), sep='separator', end='end_character', ...)
ar
hw
Multiple Arguments:
es
sep Parameter:
M
The optional sep argument allows you to specify a custom separator (e.g., sep='-' or sep='* ').
end Parameter:
The optional end argument defines what to print at the end of the line. By default, it's a newline character
('\n'), which moves the cursor to the next line. Changing it (e.g., end=' ' or end='') keeps subsequent prints on
the same line.
In [22]: # Basic output
print("Hello, World!")
# Printing multiple items with default space separator
print("My", "name", "is", "James") # Output: My name is James
# Using a custom separator
print("My", "name", "is", "James", sep="**") # Output: My**name**is**James
#
# Using the 'end' parameter to keep output on the same line
print("Today is Monday,", end=" ")
print("I like string beans.") # Output: Today is Monday, I like string beans.
e
Hello, World!
nc
My name is James
My**name**is**James
ie
Today is Monday, I like string beans.
Sc
Type Conversion in Python
p.
Type conversion in Python is the process of changing a value's data type from one to another.
om
This can happen automatically (implicit conversion) or manually by the programmer (explicit conversion, also
rC
known as type casting).
re
Implicit conversion occurs automatically when the Python interpreter safely converts a "lower" data type to a
ec
"higher" one.
|L
13.5
ah
<class 'float'>
M
This is necessary when Python cannot perform implicit conversion (e.g., adding an integer and a string).
In [13]: a = 100 # int
b = "200" # string
# This would cause a TypeError: print(a + b)
# Explicitly convert the string to an integer to perform addition
result = a + int(b)
print(result) # Output: 300
300
Debugging in python
e
nc
The process of finding and fixing errors (bugs) in code is called debugging.
ie
Errors in Python code
Sc
Due to errors, a program may not execute or may generate wrong output. Python errors can be broadly
categorized into three main types:
p.
1. Syntax Errors
om
2. Logical Errors
3. Runtime Errors
rC
1. Syntax Errors
re
These errors occur when the Python interpreter finds a mistake in the structure or grammar of the code,
tu
preventing the program from running at all. Common examples include: Missing colons at the end of
ec
statements
|L
In [14]: if True
print('Here')
ar
if True
^
SyntaxError: invalid syntax
es
ah
e
output. It is difficult to identify these errors because program interprets successfully.
nc
Examples include:
ie
Sc
Using an incorrect mathematical formula for a calculation.
To find the average of two numbers 10 and 12, if we write the code 10 + 12/2, it would run successfully and
p.
produce the result 16.0, which is wrong. The correct code to find the average is (10 + 12)/2 and the output will
om
be 11.0
rC
In [20]: average= 10 + 12/2
print("Average: ", average)
re
Average: 16.0
ec
Average: 11.0
|L
3. Runtime Errors
ar
A runtime error causes abnormal termination of program while it is executing. A runtime errors is when the
hw
statement is correct syntactically, but the interpreter can not execute it.
es
For example,
ah
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-21-de5770b9f362> in <module>()
1 a=10
2 b=0
----> 3 c=a/b
4 print("c: ", c)
e
nc
In [23]: name=shyam
ie
print(name)
Sc
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-23-3c17deb64c97> in <module>()
p.
----> 1 name=shyam
om
2 print(name)
In [24]: add="seven"+3
print(add)
tu
---------------------------------------------------------------------------
ec
----> 1 add="seven"+3
2 print(add)
ar
1. Empty Statement
ce
A statement which does nothing is called empty statement or Null statement. In python, an
empty statement is pass statement.
en
ci
Syntax
S
pass
p.
In [4]: for i in range(1,11):
if (i==5): om
rC
pass
else:
print(i, end=" ")
re
tu
1 2 3 4 6 7 8 9 10
ec
2. Simple Statement
|L
Any single executable statement is called a simple statement in Python. For example,
ar
hw
Compound Statement
A group of statements executed as a unit are called compound statements. Compound
statement has a header line and a body:
Header line
It begins with a keyword and ends with a colon(:)
Body
Body consists of one or more Python statements each indented inside the header line.
In [11]: num=int(input("Enter the number: "))
if num>0: #header line
print("Great!") #Body
print("Your entered positive number.")
elif num<0: #header line
print("Oh!") #Body
print("Your entered negative number.")
else: #header line
print("Hmm!") #Body
print("Your entered 0.")
ce
if and for statements are example of control statements.
en
ci
Control Statements
S
p.
In a program, statements are executed sequentially, selectively and iteratively. Every
programming language provides constructs to support sequence, selection and iteration.
Sequence
om
rC
In this, statements are executed sequentially. This is the default flow of the program.
re
tu
ec
|L
ar
hw
es
ah
M
Selection
Selection means the execution of statements depends on a condition test. if condition
evaluates to True, then statements following the condition are executed. Otherwise, a different
set of statements are executed. For this, if-else, if-elif-else are used.
ce
en
S ci
Iteration
p.
om
Iteration means repetition of set of statements depending upon a condition test. Till the
condition is true, set of statements are repeated. As soon as the condition becomes false, the
repetition stops. For loop and while loop are used for iteration in Python.
rC
re
tu
ec
|L
ar
hw
es
ah
M
if-else statements
Usually, statements are executed one after another in a program. However, there are sitution
when we have more than one option to choose from based on certain condition. This is done
using if-else conditional or selection statements. There are three ways to write if-else
statements:
1. if statement
It executes the statements inside if, when the condition is true.
ce
In [1]: age=int(input("Enter your age: "))
if age>=18:
en
print("You can cast your vote.")
ci
You can cast your vote.
S
p.
2. if-else statement
om
It executes the statements inside if when the condition is true otherwise executes the
statements inside else.
rC
if age>=18:
print("You can cast your vote.")
tu
else:
ec
3. if-elif-else statement
hw
It checks multiple conditions and executes statements accordingly. Meaning of elif is elseif.
es
if num>0:
print("Your entered positive number.")
M
elif num<0:
print("Your entered negative number.")
else:
print("Your entered 0.")
for loop
The for keyword is used to create a for loop.
In [5]: for x in range(1, 9):
print(x, end=" ")
1 2 3 4 5 6 7 8
ce
With the while loop we can execute a set of statements as long as a condition is true.
en
ci
In [9]: i = 1
while i < 6:
S
print(i, end=" ")
i += 1
p.
1 2 3 4 5
om
rC
re
tu
ec
|L
ar
hw
es
ah
M
List
List is a mutable datatype in python that can store a sequence of values of any type. e.g. L=
[1,2,3,4,5] Here, L is a list of integers.
In [3]: L = [1,2,3,4,5]
print("List is: ", L)
ce
In [2]: L = [1,2,3,'a','b', "abc"]
en
print("Mixed Datatype list: ", L)
S ci
KeyPoints about List
p.
om
1. List is a mutable datatype i.e. modifiable. The elements of list can be modified.
2. List elements can be of any type.
rC
3. Values of elements in list can be changed inplace.
4. List can be empty i.e. without any element and is written as L= []
re
In [39]: L= [1,2,3,4,5]
tu
L[2]= 10
ec
print(" Updated list is: ", L) #Values of elements in list can be changed in
Nested List
hw
List can have another list as an element e.g. L= [1,2,[3,4],5,6]. Here, List element at index 2 is
a list itself. So, elements are accessed as L[2][0] giving element 3 and L[2][1] giving element
es
4.
ah
In [8]: L= [1,2,[3,4],5,6]
M
Creating List
To create a list, put a number of elements in the square bracket separated with commas. e.g.
In [ ]: L= [] # Empty List
L= [1,2,3,4] # List of integers
L= ['a','b','c'] # List of characters
L= ["abc","def","ghi"] # List of string
Empty List
Empty list can be created using two ways.
1. L= []
2. L= list()
ce
Traversing a List
en
Traversing a list means accessing and processing each element of the list. Each element of
ci
the list can be accessed or traverse using a for loop or while loop.
S
p.
(A) List traversal using for loop:
In [3]: L=[1,5,10,15,20, 25,30]
for item in L:
om
rC
print(item, end=" ")
1 5 10 15 20 25 30
re
tu
for i in range(len(L)):
print(L[i],end=" ")
ar
1 5 10 15 20 25 30
hw
1 5 10 15 20 25 30
List Manipulation
In Python, list manipulation means modifying a list after it has been created. This is done
using various built-in methods, operators, and functions.
All methods are functions, but not all functions are methods.
ce
en
S ci
p.
om
rC
re
tu
len()
ec
length=len(L)
print("\nLength of the List is: ",length)
ar
max()
ah
maximum=max(L)
print("\nMaximum element in the List is: ",maximum)
sum()
ce
In [4]: L=[100,5,20,15,40, 15,10]
total=sum(L)
en
print("\nSum of all elements in the list is: ",total)
ci
Sum of all elements in the list is: 205
S
p.
sorted()
In [3]: L=[100,5,20,15,40, 15,10] om
rC
L1=sorted(L)
print("\nThe sorted list is:", L1)
re
The sorted list is: [5, 10, 15, 15, 20, 40, 100]
tu
ec
list()
|L
In [2]: string="Maheshwar"
L2=list(string)
ar
The list formed from given string is: ['M', 'a', 'h', 'e', 's', 'h', 'w',
es
'a', 'r']
ah
List Methods
M
List methods are functions called on a specific list object using the dot syntax (e.g.,
my_list.append(item)).
These methods often modify the list in-place.
ce
en
S ci
p.
om
rC
re
tu
append()
ec
|L
List after append is: [100, 5, 20, 15, 40, 15, 10, 75]
hw
extend()
es
ah
[Link](L3)
print("Extended list L is: ", L)
Extended list L is: [100, 5, 20, 15, 40, 15, 10, 100, 200, 300, 400, 500]
The main difference is that append() adds a single element to a list, even if that element is
another list, while extend() adds multiple elements from an iterable (like a list, tuple, or string)
to the list individually. For example,
In [3]: L=[100,5,20,15,40, 15,10]
L1=[2,4,8]
[Link](L1)
print("List after append is: ", L)
L=[100,5,20,15,40, 15,10]
[Link](L1)
print("\nList after extend is: ", L)
List after append is: [100, 5, 20, 15, 40, 15, 10, [2, 4, 8]]
List after extend is: [100, 5, 20, 15, 40, 15, 10, 2, 4, 8]
clear()
ce
In [24]: L=[100,5,20,15,40, 15,10]
en
[Link]()
print("\nlist after clear() method is: ",L)
S ci
list after clear() method is: []
p.
copy()
om
rC
In [26]: L=[100,5,20,15,40, 15,10]
L1=[Link]()
print("\nCopied list L1 is: ",L1)
re
tu
count()
ar
index()
In [29]: L=[100,5,20,15,40, 15,10]
index=[Link](15)
print("The first occurance of the item is: ", index)
The list after insertion is: [100, 5, 20, 15, 50, 40, 15, 10]
ce
en
pop()
ci
In [1]: L=[100,5,20,15,40, 15,10]
S
[Link]()
print("The list after pop() is called: ",L)
p.
i=int(input("Enter the position: "))
om
[Link](i) #pop() item from a specific position
print("The list after pop() is called: ",L)
The list after pop() is called: [100, 5, 20, 15, 40, 15]
rC
Enter the position: 3
The list after pop() is called: [100, 5, 20, 40, 15]
re
tu
remove()
ec
[Link](15)
print("The list after removal is: ",L)
ar
The list after removal is: [100, 5, 20, 40, 15, 10]
hw
In Python, the primary difference that the remove() method deletes an element by its value,
while the pop() method deletes an element by its index.
M
Additionally, pop() returns the removed element, whereas remove() does not return anything.
In [1]: L=[100,5,20,15,40, 15,10]
i=int(input("Enter the index of the element: "))
item=[Link](i)
print("\nThe deleted element is: ", item)
print("\nThe list after deletion is: ", L)
L=[100,5,20,15,40, 15,10]
ele=int(input("\nEnter the element to be deleted: "))
item=[Link](ele)
print("\nThe deleted element is: ", item)
print("\nThe list after deletion is: ", L)
ce
The list after deletion is: [100, 5, 20, 40, 15, 10]
en
Enter the element to be deleted: 15
ci
The deleted element is: None
S
p.
The list after deletion is: [100, 5, 20, 40, 15, 10]
reverse() om
rC
In [38]: L=[1,2,3,4,5, 6, 7]
L1=[Link]() #reverse does not return anything. So, Value in L1 is
re
sort()
hw
The sort List is: [5, 10, 15, 15, 20, 40, 100]
M
1. Joining Lists
Concatenation operator + is used to perform joining operation on the lists.
In [1]: List1=[1,3,5]
List2=[6,7,8]
print(List1+List2)
ce
[1, 3, 5, 6, 7, 8]
en
ci
Important: The + operator when used with lists requres that both the operands must be
list types. A number or any other value can not be added to a list.
S
p.
In [2]: list1=[10,12,14]
list2=list1+2
print(list2)
om
---------------------------------------------------------------------------
rC
TypeError Traceback (most recent call last)
<ipython-input-2-2203921e9c87> in <module>()
re
1 list1=[10,12,14]
----> 2 list2=list1+2
tu
3 print(list2)
ec
In [37]: list1=[10,12,14]
ar
list2=list1+"abc"
print(list2)
hw
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
es
<ipython-input-37-7960175ff911> in <module>()
1 list1=[10,12,14]
ah
----> 2 list2=list1+"abc"
3 print(list2)
M
In [8]: list1=[10,12,14]
list1+=2 # 2 is not iterable
print(list1)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-31ef8ab44591> in <module>()
1 list1=[10,12,14]
----> 2 list1+=2 # 2 is not iterable
ce
3 print(list1)
en
TypeError: 'int' object is not iterable
ci
In [9]: list1=[10,12,14]
S
list1+="abc" # "abc" is iterable
print(list1)
p.
[10, 12, 14, 'a', 'b', 'c']
om
rC
2. Repeating or Replicating Lists
re
In [10]: list1=[2,4,6]
ec
list1=list1*3
print(list1)
|L
[2, 4, 6, 2, 4, 6, 2, 4, 6]
ar
L[start:stop] creates a list slice out of the list L with elements falling between indexes start
es
In [14]: list1=[10,12,14,16,18,20,22,24,30,32,34]
M
seq=list1[3:-3]
print(seq)
In normal indexing, if the resulting index is outside the list, Python raises an IndexError
Exception. In Python,simply the elements that fall between specified boundaries are returned
without raising any error.
In [17]: list1=[10,12,14,16,18,20,22,24,30,32,34]
print(list1[3:30]) #upper limit is beyond the size of the list.
print(list1[-15:7]) #lower limit is much lower.
print(list1[15:20]) #both limits are out of bound
print(list1[-15:-20]) #both limits are out of bound
L[start:stop:step]
ce
en
In [20]: list1=[10,12,14,16,18,20,22,24,30,32,34]
print(list1[0:8:2]) #include every 2nd element.
print(list1[::3]) #no start and stop given i.e. from entire list. pick
ci
print(list1[::-1]) #it will reverse list.
S
[10, 14, 18, 22]
p.
[10, 16, 22, 32]
[34, 32, 30, 24, 22, 20, 18, 16, 14, 12, 10]
om
Some Examples
rC
re
print(str1[:-3],"and",str1[-3:])
print(str1[:6],"and",str1[12:])
ec
print(str2[:])
print(str2[::2])
print(str2[:4:2])
es
computer science
ah
cmue cec
cm
M
In [13]: L1=["Python","SQL",98,96,34]
print(L1[2:6])
print(L1[0:0])
print(L1[3:-1])
list1=[1,2,3]
list2=list1
This will not make list2 as a duplicate list of list1.
It will make list2 to point to where list1 is pointing to. So any change made to list1 will
be reflected in list2 as shown in the example.
In [25]: list1=[1,2,3]
list2=list1 #this will not create a copy of list1.
print("list1: ",list1)
print("\nlist2: ",list2)
ce
list1[1]=5
print("\nlist1: ",list1)
en
print("\nlist2: ",list2)
list1: [1, 2, 3]
S ci
list2: [1, 2, 3]
p.
list1: [1, 5, 3]
list2: [1, 5, 3]
om
rC
To make a copy of list1, there are two options:
re
In [26]: list1=[1,2,3]
ar
list2=list(list1)
print("\nlist1: ",list1)
hw
print("\nlist2: ",list2)
list1[1]=5
es
print("\nlist1: ",list1)
print("\nlist2: ",list2)
ah
list1: [1, 2, 3]
M
list2: [1, 2, 3]
list1: [1, 5, 3]
list2: [1, 2, 3]
It is now clear that any change made in the list1 are not reflected to list2.
Using copy() method
In [27]: list1=[1,2,3]
list2=[Link]()
print("\nlist1: ",list1)
print("\nlist2: ",list2)
list1[1]=5
print("\nlist1: ",list1)
print("\nlist2: ",list2)
list1: [1, 2, 3]
ce
list2: [1, 2, 3]
list1: [1, 5, 3]
en
list2: [1, 2, 3]
ci
S
Using list slice
p.
In [29]: list1=[1,2,3]
list2=list1[:]
print("\nlist1: ",list1)
om
rC
print("\nlist2: ",list2)
list2[1]=5
re
print("\nlist1: ",list1)
print("\nlist2: ",list2)
tu
ec
list1: [1, 2, 3]
|L
list2: [1, 2, 3]
list1: [1, 2, 3]
ar
list2: [1, 5, 3]
hw
es
ah
M
Dictionary
In Pytho, Dictionary is a mappig between set of keys and a set of values.
A key-value pair is called an item. A key is separated from its value by a colon(:) and items are
separated by commas(,).
Items in dictionaries are unordered i.e. we may not get back the data in the same order in
which we had entered the data initially in the dictionary.
ce
en
S ci
p.
om
rC
Example
re
In [1]: D={1:95,2:99,3:67,4:78,5:50}
print("The dictionary is: ",D)
tu
Items in the dictionary are: dict_items([(1, 95), (2, 99), (3, 67), (4, 78),
(5, 50)])
hw
Characteristics of a Dictionary
M
Creating a Ditionary
To create a dictionary, the key:value pair are included in curly({}) braces.
Syntax
dictionary_name={key1:value1,key2:value2...}
Dictionary 1 is: {}
Dictioanry 2 is: {1: 'Banana', 2: 'Mango', 3: 'Apple'}
ce
In [12]: dict1=dict()
en
dict1[1]="Banana"
dict1[2]="Mango"
ci
print("Dictionary 1 is: ", dict1)
S
Dictionary 1 is: {1: 'Banana', 2: 'Mango'}
p.
In [13]: dict2=dict(1='Apple',2='Grapes',3='Papaya')
print("Dictionary 2 is: ", dict2)
This is because dict() function takes keys as an argument and values of the keys as arguments
values. Means the keys must be valid identifier. As, a variable name cannot start with a number.
ar
In [14]: dict2=dict([(1,"Apple"),(2,"Grapes"),(3,"Papaya")])
print("The dictionary 2 is: ",dict2)
ah
If we give mutable type as key, Python will give error as: "unhashable type". For example,
In [3]: dict1={[1,2]:"apple",[3,4]:"Mango"}
print("The dictionary is: ",dict1)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-671b1d6a5c22> in <module>()
----> 1 dict1={[1,2]:"apple",[3,4]:"Mango"}
2 print("The dictionary is: ",dict1)
Traversing a dictionary
ce
Each item of a dictionary can be accessed or traversed using for loop. For example,
en
In [1]: #Method 1
ci
S
dict2={1:"Banana",2:"Mango",3:"Apple"}
for key in dict2:
p.
print(key,':',dict2[key],end="|| ")
In [2]: # Method 2
om
rC
dict2={1:"Banana",2:"Mango",3:"Apple"}
re
len()
In [8]: D={1:'Car',23:'Bike',3:'Truck',24:'Planes',15:'Bus'}
length=len(D)
ce
print("\nThe length of the dictionary is: ",length)
en
The length of the dictionary is: 5
S ci
sorted()
p.
In [10]: D={1:'Car',23:'Bike',3:'Truck',24:'Planes',15:'Bus'}
sorted_dictionary=sorted(D)
om
print("\nThe sorted list of dictionary keys is: ",sorted_dictionary )
rC
The sorted list of dictionary keys is: [1, 3, 15, 23, 24]
re
tu
clear()
tu
ec
In [11]: car = {
"brand": "Ford",
|L
"model": "Mustang",
"year": 1964
}
ar
hw
[Link]()
print(car)
es
{}
ah
copy()
M
In [12]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print("The dictionary x is: ",x)
Mustang
ce
items()
en
ci
In [14]: car = {
"brand": "Ford",
S
"model": "Mustang",
"year": 1964
p.
}
om
x = [Link]()
print(x)
rC
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
re
keys()
tu
ec
In [15]: car = {
"brand": "Ford",
|L
"model": "Mustang",
"year": 1964
ar
}
hw
x = [Link]()
print(x)
es
pop()
M
In [17]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
removed_value=[Link]("model")
print(car)
print("The removed value is: ",removed_value)
ce
The removed item is: ('year', 1964)
en
update()
S ci
In [20]: car = {
"brand": "Ford",
p.
"model": "Mustang",
om
"year": 1964
}
rC
[Link]({"color": "White"})
print(car)
re
values()
|L
In [21]: car = {
ar
"brand": "Ford",
"model": "Mustang",
hw
"year": 1964
}
es
x = [Link]()
print(x)
ah
ce
Difference between pop() and del
en
ci
The main difference is that the dictionary pop() method returns the value of the removed item,
while the del statement does not return any value.
S
pop()
p.
The pop() method is used when you need to remove a key-value pair and simultaneously use
the value that was associated with the key.
del
om
It simply deletes the item. The value is not accessible after the operation.
rC
re
In [31]: list1=[1,2,3,5,1,3,7,8,9,4,2,6,2,7,4,1,6,8,6,4,1,8,9,8,9,3,5,6,7,2,4,7,5,1,4,5
dict1={}
|L
for i in list1:
if i in dict1:
ar
dict1[i]+=1
else:
hw
dict1[i]=1
for i in dict1:
print(i, "appears ", dict1[i])
es
1 appears 5
ah
2 appears 4
3 appears 3
M
5 appears 4
7 appears 4
8 appears 4
9 appears 3
4 appears 5
6 appears 4
11 appears 1
Nested dictionary
In [16]: info={1:{'name': 'Mahesh','Post': 'PGT', 'School': 'GBSSS J J Colony Bawana'},
2:{'name': 'Ankit', 'Post': 'TGT', 'School':'GBSSS J J Colony Bawana' }
}
for i in info:
print("Employee ", i,":")
print("Name: ", info[i]['name'] )
print("Post: ", info[i]['Post'])
print("School: ", info[i]['School'])
print("\n")
Employee 1 :
ce
Name: Mahesh
Post: PGT
en
School: GBSSS J J Colony Bawana
ci
Employee 2 :
S
Name: Ankit
Post: TGT
p.
School: GBSSS J J Colony Bawana
om
rC
In [10]: dict1={'a':1,'e':2,'i':3,'o':4,'u':5}
ec
dict2={}
for i in dict1:
|L
dict2[dict1[i]]=i
print(dict1)
print(dict2)
ar
Installing NumPy
NumPy can be installed by typing following command:
ce
Array
en
ci
An array is a datatype used to store multiple elements where each element is of same type.
S
Important characteristics of array
p.
1. Each element of array is of same datatype.
om
2. The entire array is stored contiguously in memory. This makes operations on array fast.
rC
3. Each element of the array is identified or referred using the name of the array along with the index of the
element.
re
tu
To create an array and to use its methods, first import NumPy library. The NumPy's array function converts a given
list into an array. For example,
In [3]: import numpy as np
arr1=[Link]([11,-12,33])
print(arr1)
[ 11 -12 33]
2-D arrays are created by passing nested lists to the array() function.
[[1 2 3]
ce
[4 5 6]]
en
Rank of an array
S ci
The number of axes of an array is called rank of that array. 2-D array has two axes(i.e axis=0 and axis=1). So, 2-D
array has rank [Link] 1-D array has one axis(i.e. axis=0). So, 1-D array has rank 1.
p.
Attributes of NumPy Array om
rC
1. [Link]
re
print([Link])
ec
2
|L
2. [Link]
ar
(2, 3)
ah
3. [Link]
M
4. [Link]
It is the data type of the elements of the array.
In [8]: import numpy as py
arr1=[Link]([[1,2,3],[4,5,6]])
print([Link])
int32
5. [Link]
It specifies the size in bytes of each element of the array.
ce
Other Ways of Creating NumPy Arrays
en
ci
1. Using array function with specified data type
S
In [10]: import numpy as py
p.
arr1=[Link]([[1,2,3],[4,5,6]], dtype=float)
print(arr1)
[[ 1.
[ 4.
2.
5.
3.]
6.]]
om
rC
arr1=[Link]((2,2))
ec
print(arr1)
[[ 0. 0.]
|L
[ 0. 0.]]
ar
Default data type of array created using zero() function is float. This can be changed using dtype
attribute.
hw
print(arr1)
[[0 0]
ah
[0 0]]
M
[[ 1. 1.]
[ 1. 1.]]
Default data type of array created using ones() function is float. This can be changed using dtype
attribute.
In [19]: import numpy as py
arr1=[Link]((2,2), dtype=int)
print(arr1)
[[1 1]
[1 1]]
[0 1 2 3 4 5 6 7 8 9]
ce
In [5]: import numpy as py
en
arr1=[Link](-2,24,3)
print(arr1)
ci
[-2 1 4 7 10 13 16 19 22]
S
p.
Indexing and Slicing
Indexing
om
rC
The indexing of 1-D array is simple. An array containan ordered collection of data elements where each element is
re
referenced by its index. Index starts from zero e.g. first element has index 0, second element has index 1 and so
on.
tu
arr1=[Link]([2,6,8,19,20,40,30])
print(arr1)
|L
print(arr1[3])
print(arr1[0])
ar
[ 2 6 8 19 20 40 30]
19
2
hw
For 2-D arrays, indexing for both dimensions starts from 0 and each element is referenced through two indexes i
es
and j where i represents the row number and j represents the column number.
ah
print(arr1)
print(arr1[1,2])
print(arr1[1,1])
[[1 2 3]
[4 5 6]]
6
5
Slicing
Using slicing, a part of array can be extracted. To define which part of the array is to be sliced, the start and end
index values can be specified with the array name.
In [17]: import numpy as py
arr1=[Link]([2,6,8,19,20,40,30])
print("Complete array:", arr1)
print("Sliced array:", arr1[2:6])
Complete array:
[[2 3 4]
[5 6 7]
[8 9 1]]
ce
Sliced array:
[[2 3]
en
[5 6]]
ci
Operations on Array
S
p.
Arithmetic Opeartions
In [3]: import numpy as np
om
rC
arr1=[Link]([[3,6],[4,2]])
arr2=[Link]([[10,20],[15,12]])
print("arr1:\n ",arr1)
re
print("\narr2:\n ",arr2)
print("\narr1 + arr2:\n ",arr1+arr2)
tu
arr1:
ec
[[3 6]
[4 2]]
|L
arr2:
[[10 20]
[15 12]]
ar
arr1 + arr2:
hw
[[13 26]
[19 14]]
es
arr2=[Link]([[10,20],[15,12]])
print("arr1:\n ",arr1)
print("\narr2:\n ",arr2)
M
arr1:
[[3 6]
[4 2]]
arr2:
[[10 20]
[15 12]]
arr1 - arr2:
[[ 7 14]
[11 10]]
In [6]: import numpy as np
arr1=[Link]([[3,6],[4,2]])
arr2=[Link]([[10,20],[15,12]])
print("arr1:\n ",arr1)
print("\narr2:\n ",arr2)
print("\narr2 * arr1:\n ",arr2*arr1)
arr1:
[[3 6]
[4 2]]
arr2:
[[10 20]
[15 12]]
arr1 * arr2:
[[ 30 120]
ce
[ 60 24]]
en
In [7]: import numpy as np
arr1=[Link]([[3,6],[4,2]])
arr2=[Link]([[10,20],[15,12]])
ci
print("arr1:\n ",arr1)
S
print("\narr2:\n ",arr2)
print("\narr2 / arr1:\n ",arr2/arr1)
p.
arr1:
[[3 6]
[4 2]]
arr2:
om
rC
[[10 20]
[15 12]]
re
arr1 / arr2:
[[ 3.33333333 3.33333333]
tu
[ 3.75 6. ]]
ec
arr2=[Link]([[10,20],[15,12]])
print("arr1:\n ",arr1)
print("\narr1 power 3:\n ",arr1)
ar
arr1:
[[3 6]
hw
[4 2]]
arr1 power 3:
es
[[3 6]
[4 2]]
ah
M
In [10]: import numpy as np
arr1=[Link]([[3,6],[4,2]])
arr2=[Link]([[10,20],[15,12]])
print("arr1:\n ",arr1)
print("\narr2:\n ",arr2)
print("\narr2%arr1:\n ",arr2%arr1)
arr1:
[[3 6]
[4 2]]
arr2:
[[10 20]
[15 12]]
arr2%arr1:
[[1 2]
ce
[3 0]]
en
Transpose
ci
Transposing an array turns its rows into columns and columns into rows.
S
p.
In [15]: import numpy as np
arr1=[Link]([[3,6],[4,2]])
print("The arrar arr1 is:\n ", arr1)
print("The transpose of arr1 is:\n ",[Link]())
[[3 4]
[6 2]]
tu
ec
Sorting
|L
In 2-D array, sorting can be done along either of the axes i.e. row-wise or column-wise. By
hw
[Link]()
print("The sorted arr1 is:\n ",arr1)
M
When axis=0 sorting is done column-wise, which means each column is sorted in ascending
order.
In [17]: import numpy as np
arr1=[Link]([[13,6],[4,2]])
print("The arrar arr1 is:\n ", arr1)
[Link](axis=0)
print("The sorted arr1 is:\n ",arr1)
Concatenating Arrays
ce
Concatenation means joining two or more arrays. [Link]() function is used for this purpose.
Concatenating 1-D array means appending the sequences one after the another.
en
In [4]: import numpy as np
ci
arr1=[Link]([1,2,3,4,5])
arr2=[Link]([6,7,8,9,10])
S
[Link]((arr1,arr2))
p.
Out[4]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
om
**For 2-D arrays, all the dimensions of the arrays to be concatenated must match exactly
except for the dimension or axis along which they need to be joined.**
rC
In [17]: import numpy as np
arr1=[Link]([[1,0],[0,1]])
arr2=[Link]([[10,10],[10,10]])
re
[Link]((arr1,arr2))
tu
[ 0, 1],
[10, 10],
|L
[10, 10]])
By default, concatenation happens along axis=0. To do column-wise, axis is set to 1 i.e axis=1
ar
arr1=[Link]([[1,0],[0,1]])
arr2=[Link]([[10,10],[10,10]])
[Link]((arr1,arr2),axis=1)
es
[ 0, 1, 10, 10]])
M
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-19-9b62c3f1431a> in <module>()
2 arr1=[Link]([[1,0],[0,1]])
3 arr2=[Link]([[10,10,10],[10,10,10]])
----> 4 [Link]((arr1,arr2))
ValueError: all the input array dimensions except for the concatenation axis must match exa
ctly
Reshaping Arrays
ce
Original array arr1 is: [10 11 12 13 14 15 16 17 18 19 20 21]
en
[[10 11 12 13]
[14 15 16 17]
[18 19 20 21]]
S ci
The modified array is:
[[10 11 12 13 14 15]
p.
[16 17 18 19 20 21]]
arr1=[Link]([13,78,23,56,83,67,20,19,79])
print("The array arr1 is: ", arr1)
ec
[[30 10 56 78 45]
[60 34 98 56 23]]
M
2. min() function
3. sum() function
ce
In [31]: import numpy as np
arr1=[Link]([13,78,23,56,83,67,20,19,79])
en
print("The array arr1 is: ", arr1)
print("\nThe sum of all elements in the array is: ", [Link]())
ci
The array arr1 is: [13 78 23 56 83 67 20 19 79]
S
The sum of all elements in the array is: 438
p.
In [36]: import numpy as np
arr1=[Link]([[30,10,56,78,45],[60,34,98,56,23]])
print("The array arr1 is: \n", arr1)
om
print("\nThe row-wise sum of elements in array is: ", [Link](axis=1))
rC
print("\nThe column-wise sum of elements in array is: ", [Link](axis=0))
[60 34 98 56 23]]
tu
4. mean() function
ar
arr1=[Link]([13,78,23,56,83,67,20,19,79])
print("The array arr1 is: ", arr1)
print("\nThe mean of all elements in the array is: ", [Link]())
es
The column-wise mean of elements in array is: [ 45. 22. 77. 67. 34.]
5. std() function
ce
print("\nThe column-wise standard deviation of elements in array is: ", [Link](axis=0))
en
[[30 10 56 78 45]
[60 34 98 56 23]]
ci
The row-wise standard deviation of elements in array is: [ 23.03388808 25.83331183]
S
The column-wise standard deviation of elements in array is: [ 15. 12. 21. 11. 11.]
p.
om
rC
re
tu
ec
|L
ar
hw
es
ah
M
REFERENCES
ce
4. Google. Gemini (AI tool). Retrieved from [Link]
en
5. Google. Google Photos (Images used). Retrieved from
ci
[Link]
S
6. Project Jupyter. (n.d.). Jupyter Notebook (Software). Retrieved from
p.
[Link]
om
rC
re
tu
ec
|L
ar
hw
es
ah
M