Python Operators (Unit 2)
Operators are used to perform operations on variables and values. In the example
below, we use the + operator to add together two values:
Example : print(10 + 5)
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Python Assignment Operators :Assignment operators are used to assign values to variables:
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
:= print(x := 3) x = 3 print(x)
Python Comparison Operators
Comparison operators are used to compare two values:
Operator Example Same As
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Python Logical Operators
Logical operators are used to combine conditional statements:
Operator Description Example
and Returns True if both statements x < 5 and x < 10
Try it »
are true
or Returns True if one of the x < 5 or x < 4 Try it »
statements is true
not Reverse the result, returns False if Not (x < 5 and x <
the result is true 10)
Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
Operator Description Example
is Returns True if both variables are the same object x is y Try it »
is not Returns True if both variables are not the same x is not y
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
Operator Description Example
in Returns True if a sequence with the specified x in y Try it »
value is present in the object
not in Returns True if a sequence with the specified x not in y
value is not present in the object
Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
Operator Name Description Example
& AND Sets each bit to 1 if both bits are 1 x&y
| OR Sets each bit to 1 if one of two bits is 1 x|y
^ XOR Sets each bit to 1 if only one of two x^y
bits is 1
~ NOT Inverts all the bits ~x
<< Zero fill left shift Shift left by pushing zeros in from the x << 2
right and let the leftmost bits fall off
>> Signed right Shift right by pushing copies of the x >> 2
shift leftmost bit in from the left, and let
the rightmost bits fall off
What are Mutable Data Types? Anything is said to be mutable when anything can be modified or
changed. The term "mutable" in Python refers to an object's capacity to modify its values. These are
frequently the things that hold a data collection. Ex: List, Dictionaries, Sets.
What are Immutable Data Types? Immutable refers to a state in which no change can occur over
time. A Python object is referred to as immutable if we cannot change its value over time. The
value of these Python objects is fixed once they are made. Ex: Tuples , String
Python mutable data types:
o Lists
o Dictionaries
o Sets
o User-Defined Classes (It depends on the user to define the characteristics of the classes)
Python immutable data types:
o Numbers (Integer, Float, Complex, Decimal, Rational & Booleans)
o Tuples
o Strings
Example of Mutable Objects in Python :
1. List : As a result of their mutable nature, lists can change their contents by incorporating
the assignment operators or the indexing operators.
1. # Python program to show that a list is a mutable data type
2. # Creating a list
3. list1 = ['Python', 'Java', 23, False, 5.3]
4. print("The original list: ", list1)
5. # Changing the value at index 2 of the list
6. list1[2]='changed'
7. print("The modified list: ", list1)
Output:
The original list: ['Python', 'Java', 23, False, 5.3]
The modified list: ['Python', 'Java', 'changed', False, 5.3]
2. Dictionary: Due to the mutability of dictionaries, we can modify them by implementing
a built-in function update or using keys as an index.
1. # Python program to show that a dictionary is a mutable data type
2. # Creating a dictionary
3. dict_ = {1: "a", 2: "b", 3: "c"}
4. print("The original dictionary: ", dict_)
5. # Changing the value of one of the keys of the dictionary
6. dict_[2]= 'changed'
7. print("The modified dictionary: ", dict_)
Output:
The original dictionary: {1: 'a', 2: 'b', 3: 'c'}
The modified dictionary: {1: 'a', 2: 'changed', 3: 'c'}
3. Set: Due to the mutability of sets, we can modify them using a built-in function (update).
1. # Python program to show that a set is a mutable data type
2. # Creating a set
3. set_ = {1, 2, 3, 4}
4. print("The original set: ", set_)
5. # Updating the set using the update function
6. update_set = {'a', 'b', 'c'}
7. set_.update(update_set)
8. print("The modified set: ", set_)
Output:
The original set: {1, 2, 3, 4}
The modified set: {1, 2, 3, 4, 'b', 'a', 'c'}
Example of Immutable Objects in Python :
int : Since int in Python is an immutable data type, we cannot change or update it. As we
previously learned, immutable objects shift their memory address whenever they are
updated.
1. # Python program to show that int is an immutable data type
2. int_ = 25
3. print('The memory address of int before updating: ', id(int_))
4. # Modifying an int object by giving a new value to it
5. int_ = 35
6. print('The memory address of int after updating: ', id(int_))
Output:
The memory address of int before updating: 11531680
The memory address of int after updating: 11532000
Float Since the float object in Python is an immutable data type, we cannot alter or update it. As
we previously learned, immutable objects shift their memory address whenever they are updated.
1. # Python program to show that float is an immutable data type
2.
3. float_ = float(34.5)
4. print('The memory address of float before updating: ', id(float_))
5.
6. # Modifying the float object by giving a new value to it
7. float_ = float(32.5)
8. print('The memory address of float after updating: ', id(float_))
Output:
The memory address of float before updating: 139992739659504
The memory address of float after updating: 139992740128048
String
Since strings in Python are immutable data structures, we cannot add or edit
any data. We encountered warnings stating that strings are not changeable
when modifying any section of the string.
Code
1. # Python program to show that a string is an immutable data type
2. # Creating a string object
3. string = 'hello peeps'
4. # Trying to modify the string object
5. string[0] = 'X'
6. print(string)
Output:
TypeError Traceback (most recent call last)
<ipython-input-3-4e0fff91061f> in <module>
3 string = 'hello peeps'
4
----> 5 string[0] = 'X'
6
7 print(string)
TypeError: 'str' object does not support item assignment
Tuple
Because tuples in Python are immutable by nature, we are unable to add or
modify any of their contents. Here is an illustration of that:
1. # Python program to show that a tuple is an immutable data type
2. # Creating a tuple object
3. tuple_ = (2, 3, 4, 5)
4. # Trying to modify the tuple object
5. tuple_[0] = 'X'
6. print(tulple_)
Output:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-e011ebc4971e> in <module>
5
6 # Trying to modify the tuple object
----> 7 tuple_[0] = 'X'
8 print(tulple_)
9
TypeError: 'tuple' object does not support item assignment
The Python id() Function :
When you define a Python object, the program sets a memory section aside. Every Python object has a
distinct address that informs the application where the item is located in memory. Every object in
Python has a distinct ID connected to the object's memory address. Use the built-in Python id()
function to read the special ID . Let's read the position of a sample string object in memory, for
instance:
1. # Python program to show how to use the id function
2. # Initializing a string object
3. string = "string"
4. # Printing the id of the string object
5. print(id(string))
Output:
140452604995952
LIST
List Declaration
Code
# a simple list
list1 = [1, 2, "Python", "Program", 15.9]
list2 = ["Amy", "Ryan", "Henry", "Emma"]
# printing the list
print(list1)
print(list2)
# printing the type of list
print(type(list1))
print(type(list2))
Output:
[1, 2, 'Python', 'Program', 15.9]
['Amy', 'Ryan', 'Henry', 'Emma']
< class ' list ' >
< class ' list ' >
Characteristics of Lists
The characteristics of the List are as follows:
o The lists are in order.
o The list element can be accessed via the index.
o The mutable type of List is
o The number of various elements can be stored in a list.
Ordered List Checking
Code
1. # example
2. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]
3. b = [ 1, 2, 5, "Ram", 3.50, "Rahul", 6 ]
4. print (a == b)
Output:
False
The indistinguishable components were remembered for the two records; however,
the subsequent rundown changed the file position of the fifth component, which is
against the rundowns' planned request. False is returned when the two lists are
compared.
Code
1. # example
2. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
3. b = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
4. a == b
Output:
True
Records forever protect the component's structure. Because of this, it is an arranged
collection of things.
Let's take a closer look at the list example.
Code
# list example in detail
emp = [ "John", 102, "USA"]
Dep1 = [ "CS",10]
Dep2 = [ "IT",11]
HOD_CS = [ 10,"Mr. Holding"]
HOD_IT = [11, "Mr. Bewon"]
print("printing employee data ...")
print(" Name : %s, ID: %d, Country: %s" %(emp[0], emp[1], emp[2]))
print("printing departments ...")
print("Department 1:\nName: %s, ID: %d\n Department 2:\n Name: %s, ID: %s"%(
Dep1[0], Dep2[1], Dep2[0], Dep2[1]))
print("HOD Details ....")
print("CS HOD Name: %s, Id: %d" %(HOD_CS[1], HOD_CS[0]))
print("IT HOD Name: %s, Id: %d" %(HOD_IT[1], HOD_IT[0]))
print(type(emp), type(Dep1), type(Dep2), type(HOD_CS), type(HOD_IT))
Output:
printing employee data...
Name : John, ID: 102, Country: USA
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
<class ' list '> <class ' list '> <class ' list '> <class ' list '> <class ' list '>
List Indexing and Splitting
The indexing procedure is carried out similarly to string processing. The slice
operator [] can be used to get to the List's components.
The index ranges from 0 to length -1. The 0th index is where the List's first element
is stored; the 1st index is where the second element is stored, and so on.
We can get the sub-list of the list using the following syntax.
1. list_varible(start:stop:step)
o The beginning indicates the beginning record position of the rundown.
o The stop signifies the last record position of the rundown.
o Within a start, the step is used to skip the nth element: stop.
The start parameter is the initial index, the step is the ending index, and the value of
the end parameter is the number of elements that are "stepped" through. The default
value for the step is one without a specific value. Inside the resultant Sub List, the
same with record start would be available, yet the one with the file finish will not.
The first element in a list appears to have an index of zero.
Consider the following example:
Code
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
# By default, the index value is 0 so its starts from the 0th element and go for index -
1.
print(list[:])
print(list[2:5])
print(list[1:6:2])
Output:
1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]
In contrast to other programming languages, Python lets you use negative indexing
as well. The negative indices are counted from the right. The index -1 represents the
final element on the List's right side, followed by the index -2 for the next member
on the left, and so on, until the last element on the left is reached.
Let's have a look at the following example where we will use negative indexing to
access the elements of the list.
Code
# negative indexing example
list = [1,2,3,4,5]
print(list[-1])
print(list[-3:])
print(list[:-1])
print(list[-3:-1])
Output:
5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
Negative indexing allows us to obtain an element, as previously mentioned. The
rightmost item in the List was returned by the first print statement in the code above.
The second print statement returned the sub-list, and so on.
Updating List Values
Due to their mutability and the slice and assignment operator's ability to update their
values, lists are Python's most adaptable data structure. Python's append () and insert
() methods can also add values to a list.
Consider the following example to update the values inside the List.
Code
# updating list values
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to the second index
list[2] = 10
print(list)
# Adding multiple-element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
Remove()
The remove() method removes the specified item.
Example
Remove "banana":
Thislist=["apple", "banana", "cherry"]
[Link]("banana")
print(Thislist)
Pop()
The pop() method removes the specified index.
thislist=["apple", "banana", "cherry"]
[Link](1)
print(thislist)
If you do not specify the index, the pop() method removes the last item.
The del keyword also removes the specified index:
Example
thislist=["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
Python List Operations
The concatenation (+) and repetition (*) operators work in the same way as they
were working with the strings. The different operations of list are
1. Repetition
2. Concatenation
3. Length
4. Iteration
5. Membership
We check how the list responds to various operators.
1. Repetition
The redundancy administrator empowers the rundown components to be rehashed on
different occasions.
Code
# repetition of list
# declaring the list
list1 = [12, 14, 16, 18, 20]
# repetition operator *
l = list1 * 2
print(l)
Output:
[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]
2. Concatenation
It concatenates the list mentioned on either side of the operator.
Code
# concatenation of two lists
# declaring the lists
list1 = [12, 14, 16, 18, 20]
list2 = [9, 10, 32, 54, 86]
# concatenation operator +
l = list1 + list2
print(l)
Output:
[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]
3. Length
It is used to get the length of the list
Code
# size of the list
# declaring the list
list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
# finding length of the list
len(list1)
Output:
4. Iteration
The for loop is used to iterate over the list elements.
Code
# iteration of the list
# declaring the list
list1 = [12, 14, 16, 39, 40]
# iterating
for i in list1:
print(i)
Output:
12
14
16
39
40
5. Membership
It returns true if a particular item exists in a particular list otherwise false.
Code
# membership of the list
# declaring the list
list1 = [100, 200, 300, 400, 500]
# true will be printed if value exists
# and false if not
print(600 in list1)
print(700 in list1)
print(1040 in list1)
print(300 in list1)
print(100 in list1)
print(500 in list1)
Output:
False
False
False
True
True
True
Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings,
which can be iterated as follows.
Code
# iterating a list
list = ["John", "David", "James", "Jonathan"]
for i in list:
# The i variable will iterate over the elements of the List and contains each elemen
t in each iteration.
print(i)
Output:
John
David
James
Jonathan
Adding Elements to the List
The append() function in Python can add a new item to the List. In any case, the
annex() capability can enhance the finish of the rundown.
Consider the accompanying model, where we take the components of the rundown
from the client and print the rundown on the control center.
Code
#Declaring the empty list
l =[]
#Number of elements will be entered by the user
n = int(input("Enter the number of elements in the list:"))
# for loop to take the input
for i in range(0,n):
# The input is taken from the user and added to the list as the item
[Link](input("Enter the item:"))
print("printing the list items..")
# traversal loop to print the list items
for i in l:
print(i, end = " ")
Output:
Enter the number of elements in the list:10
Enter the item:32
Enter the item:56
Enter the item:81
Enter the item:2
Enter the item:34
Enter the item:65
Enter the item:09
Enter the item:66
Enter the item:12
Enter the item:18
printing the list items..
32 56 81 2 34 65 09 66 12 18
Removing Elements from the List
The remove() function in Python can remove an element from the List. To
comprehend this idea, look at the example that follows.
Example -
Code
list = [0,1,2,3,4]
print("printing original list: ");
for i in list:
print(i,end=" ")
[Link](2)
print("\nprinting the list after the removal of first element...")
for i in list:
print(i,end=" ")
Output:
printing original list:
01234
printing the list after the removal of first element...
0134
Python List Built-in Functions
Python provides the following built-in functions, which can be used with the lists.
1. len()
2. max()
3. min()
len( )
It is used to calculate the length of the list.
Code
# size of the list
# declaring the list
list1 = [12, 16, 18, 20, 39, 40]
# finding length of the list
len(list1)
Output:
Max( )
It returns the maximum element of the list
Code
# maximum of the list
list1 = [103, 675, 321, 782, 200]
# large element in the list
print(max(list1))
Output:
782
Min( )
It returns the minimum element of the list
Code
# minimum of the list
list1 = [103, 675, 321, 782, 200]
# smallest element in the list
print(min(list1))
Output:
103
Let's have a look at the few list examples.
Example: 1- Create a program to eliminate the List's duplicate items.
Code
list1 = [1,2,2,3,55,98,65,65,13,29]
# Declare an empty list that will store unique values
list2 = []
for i in list1:
if i not in list2:
[Link](i)
print(list2)
Output:
[1, 2, 3, 55, 98, 65, 13, 29]
Example:2- Compose a program to track down the amount of the component in the
rundown.
Code
1. list1 = [3,4,5,9,10,12,24]
2. sum = 0
3. for i in list1:
4. sum = sum+i
5. print("The sum is:",sum)
Output:
The sum is: 67
In [8]:
Example: 3- Compose the program to find the rundowns comprise of somewhere
around one normal component.
Code
1. list1 = [1,2,3,4,5,6]
2. list2 = [7,8,9,2,10]
3. for x in list1:
4. for y in list2:
5. if x == y:
6. print("The common element is:",x)
Output:
The common element is: 2