[Type the document title]
Python Lists
In Python, a list is a collection of ordered and indexed elements of different data
types. In Python, the list and its elements are mutable. That means, the list and its
elements can be modified at any time in the program. In Python, the list data type
(data structure) has implemented with a class known as a list. All the elements of a
list must be enclosed in square brackets, and each element must be separated with a
comma symbol. In Python, the list elements are organized as an array of elements
of different data types. All the elements of a list are ordered and they are indexed.
Here, the index starts from '0' (zero) and ends with 'number of elements - 1'.
In Python, the list elements are also indexed with negative numbers from the
last element to the first element in the list. Here, the negative index begins
with -1 at the last element and decreased by one for each element from the
last element to the first element.
Creating a list in Python
The general syntax for creating a list is as follows.
Syntax
list_name = [element_1, element_2, element_3, ...]
For example, consider the following code for creating a list which stores the details
of a student.
Python code to illustrate creating a list
student_data = [1, 'Rama', '2nd Year', 'CSE', 85.80]
print(student_data)
When we run the above code, it produces the output as follows.
CMR INSTITUTE OF TECHNOLOGY Page 1
[Type the document title]
In Python, a list can also be created using list() constructor. The list() constructor
takes only one argument.
Syntax
list_name = list([element_1, element_2, element_3, ...])
For example, consider the following code for creating a list using list() constructor
which stores the details of a student.
CMR INSTITUTE OF TECHNOLOGY Page 2
[Type the document title]
Python code to illustrate creating a list using list() constructor.
student_data = list([1, 'Rama', '2nd Year', 'CSE', 85.80])
print(type(student_data))
print(student_data)
When we run the above code, it produces the output as follows.
Accessing Elements of a list in Python
In Python, the list elements are organized using index values that start with '0'
(zero) at first element and ends with 'length of the list - 1' at last element. The
individual elements of a list are accessed using the index values.
Syntax
list_name[index]
CMR INSTITUTE OF TECHNOLOGY Page 3
[Type the document title]
For example, consider the following code for accessing individual elements of a
list.
Python code to illustrate accessing elements of a list.
student_data = [1, 'Rama', '2nd Year', 'CSE', 85.80]
print(f'Roll Number: {student_data[0]}\n'
f'Name of the Student: {student_data[1]}\n'
f'Branch: {student_data[3]}\n'
f'Year: {student_data[2]}\n'
f'Percentage: {student_data[4]}')
When we run the above code, it produces the output as follows.
List Slicing
In Python, we can also access a subset of elements from a list using slicing. We
can access any subset of elements from a specified starting index to ending index.
In list slicing, the default starting index is '0' and the default ending is 'length of the
list - 1'.
CMR INSTITUTE OF TECHNOLOGY Page 4
[Type the document title]
Syntax
list_name[starting_index : ending_index]
For example, consider the following code for accessing a subset of elements from a
list.
Python code to illustrate accessing a subset of elements from a list.
student_data = [1, 'Rama', '2nd Year', 'CSE', 85.80]
print(student_data[2:4]) # Accessing elements from index 2 to 3
print(student_data[:4]) # Accessing elements from index 0 to 3
print(student_data[2:]) # Accessing elements from index 2 to last element
When we run the above code, it produces the output as follows.
Changing an Element of a list in Python
In Python, an element of a list can be changed at any time using index value.
Syntax
list_name[index] = new_value
CMR INSTITUTE OF TECHNOLOGY Page 5
[Type the document title]
For example, consider the following code for changing an element of a list.
Python code to illustrate changing an element of a list.
student_data = [1, 'Rama', '2nd Year', 'CSE', 85.80]
student_data[1] = 'Seetha'
print(student_data)
When we run the above code, it produces the output as follows.
Looping through a list in Python
In Python, we can loop through a list using for statement with membership
operator in.
For example, consider the following code to loop through a list.
Python code to illustrate loop through a list.
student_data = [1, 'Rama', '2nd Year', 'CSE', 85.80]
CMR INSTITUTE OF TECHNOLOGY Page 6
[Type the document title]
for element in student_data:
print(f'Element from the List is - {element}')
When we run the above code, it produces the output as follows.
Existence of an element in a list in Python
In Python, we can test whether an element is present in a list or not using
membership operator 'in'.
For example, consider the following code to test the existence of an element in a
list.
Finding the length of a list in Python
CMR INSTITUTE OF TECHNOLOGY Page 7
[Type the document title]
The Python provides a built-in function len( ) to find the length of a list. Here, the
length of a list is the total number of elements in that list.
For example, consider the following code to find the length of a list.
Python code to illustrate the length of a list.
student_data = [1, 'Rama', '2nd Year', 'CSE', 85.80]
list_length = len(student_data)
print(f'Length of the list is {list_length}')
When we run the above code, it produces the output as follows.
Adding an element to the list in Python
Adding an element to the existing list can be performed using the following built-
in methods.
append(value)
insert(index, value)
CMR INSTITUTE OF TECHNOLOGY Page 8
[Type the document title]
append(value) - This method adds a new element at the end of the list.
For example, consider the following code.
Python code to illustrate append() method in a list.
student_data = [1, 'Rama', '2nd Year', 'CSE', 85.80]
student_data.append('promoted')
print(f'The list after append is\n{student_data}')
When we run the above code, it produces the output as follows.
insert(index, value) - This method inserts a new element at the specified index of
the list.
For example, consider the following code.
Python code to illustrate insert() method in a list.
student_data = [1, 'Rama', '2nd Year', 'CSE', 85.80]
student_data.insert(2, 'promoted')
CMR INSTITUTE OF TECHNOLOGY Page 9
[Type the document title]
print(f'The list after insertion at index 2 is\n{student_data}')
When we run the above code, it produces the output as follows.
When we use insert( ) method with an index value out of range then, the new
element is inserted at the end of the list.
Removing elements from a list in Python
The Python provides the following built-in methods to remove elements from a
list.
remove(value)
pop()
clear()
CMR INSTITUTE OF TECHNOLOGY Page 10
[Type the document title]
del
remove(value) - This method removes the specified element from the list. If the
specified element is not found in the list, then the execution terminates with an
error message.
pop( ) or pop(index) - This method removes the last element from the list. But,
when it is used with an index value, it removes the value at the specified index
from the list.
clear( ) - This method removes all the elements from the list. The clear( ) method
makes the list empty.
del Keyword - This keyword removes the complete list from the memory. After
del keyword used with a list, we can not use it again.
For example, consider the following code.
Python code to illustrate remove operation in a list.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(f'The list is - {my_list}')
my_list.remove(6)
print(f'The list after removing 6 is - {my_list}')
my_list.pop()
print(f'The list after pop is - {my_list}')
my_list.pop(2)
print(f'The list after pop with index 2 is - {my_list}')
my_list.clear()
print(f'The list after clear is - {my_list}')
del my_list
#print(f'The list after del keyword used is - {my_list}') # GENERATES ERROR
CMR INSTITUTE OF TECHNOLOGY Page 11
[Type the document title]
When we run the above code, it produces the output as follows.
Counting the number of time a value appears in the list
The Python provides a built-in method called count(value) to count the number of
times the given value appears in the list.
For example, consider the following code.
CMR INSTITUTE OF TECHNOLOGY Page 12
[Type the document title]
Python code to illustrate the count( ) method in a list.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 5, 2]
print(f'The list is - {my_list}')
print(f'The value 2 appears {my_list.count(2)} times in the list.')
When we run the above code, it produces the output as follows.
Extending a list
The Python provides a built-in method called extend( ) to append elements of a list
to another list. For example, consider the following example.
CMR INSTITUTE OF TECHNOLOGY Page 13
[Type the document title]
Python code to illustrate extend( ) method in a list.
my_list_1 = [1, 2, 3, 4, 5]
my_list_2 = [10, 20, 30]
my_list_1.extend(my_list_2)
print(f'The list_1 after extend is - {my_list_1}')
When we run the above code, all the elements of my_list_2 are appended
to my_list_2. So, it produces the output as follows.
Finding the index of a value in a list
The Python provides a built-in method called index( value ) to find the index of
that value in the list. If the given value not found in the list, then the execution
CMR INSTITUTE OF TECHNOLOGY Page 14
[Type the document title]
terminates with an error message ValueError: <<value>> is not in the list. For
example, consider the following example.
Python code to illustrate the index( ) method in a list.
my_list = [1, 2, 3, 4, 5]
print(f'The index of the value 4 is {my_list.index(4)}')
#print(f'The index of the value 7 is {my_list.index(7)}') # generates an error
When we run the above code, it produces the output as follows.
Finding Maximum and Minimum value in a list
The Python programming language provides built-in methods max( ) and min( ) to
find the maximum and minimum elements in a list.
CMR INSTITUTE OF TECHNOLOGY Page 15
[Type the document title]
For example, consider the following code.
Python code to illustrate max( ) and mim( ) methods in a list.
my_list = [12, 2, 5, 90, 30, 40, 3]
print(f'The maximum value in the list is - {max(my_list)}')
print(f'The minimum value in the list is - {min(my_list)}')
When we run the above code, it produces the output as follows.
The reverse of a list
CMR INSTITUTE OF TECHNOLOGY Page 16
[Type the document title]
The Python provides a built-in method reverse( ) to produce the reverse of a list.
The method reverse( ) returns None.
For example, consider the following code.
Python code to illustrate reverse( ) in a list.
my_list = [12, 2, 5, 90, 30, 40, 3]
print(f'The list is - {my_list}')
my_list.reverse()
print(f'Reverse of the list is - {my_list}')
When we run the above code, it produces the output as follows.
CMR INSTITUTE OF TECHNOLOGY Page 17
[Type the document title]
Sorting the elements of a list
The Python provides a built-in method sort( ) to sort all the elements of a list. The
method sort( ) returns None. The sort( ) method arranges the list elements in
increasing order by default. To sort the elements in decreasing order, we need to
pass an argument reverse = True to sort( ) method.
For example, consider the following code.
Python code to illustrate sort( ) in a list.
my_list = [12, 2, 5, 90, 30, 40, 3]
print(f'The list is - {my_list}')
my_list.sort()
print(f'Increasing order of the list is - {my_list}')
my_list.sort(reverse=True)
print(f'Decreasing order of the list is - {my_list}')
When we run the above code, it produces the output as follows.
In Python, the functions max( ), min( ), and sorted( ) can be used with the
list only if the list contains all elements of numerical type.
CMR INSTITUTE OF TECHNOLOGY Page 18
[Type the document title]
PythonTuple
In Python, a tuple is a collection of ordered and indexed elements of different data
types. That means tuples are similar to the lists. But, the elements of a tuple are
immutable however tuple itself is mutable. That means the elements of a tuple can
not be modified whereas entire tuple can be modified or redefined. In Python, the
tuple data type (data structure) has implemented with a class known as a tuple. All
the elements of a tuple must be enclosed in parenthesis, and each element must be
separated with a comma symbol. In Python, the tuple elements are organized as an
array of elements of different data types. All the elements of a tuple are ordered
and they are indexed. Here, the index starts from '0' (zero) and ends with 'number
of elements - 1'.
In Python, the tuple elements are also indexed with negative numbers from
the last element to the first element in the tuple. Here, the negative index
begins with -1 at the last element and decreased by one for each element
from the last element to the first element.
Creating a tuple in Python
The general syntax for creating a tuple in Python is as follows.
Syntax
tuple_name = (element_1, element_2, element_3, ...)
For example, consider the following code for creating a tuple which stores the
details of a student.
CMR INSTITUTE OF TECHNOLOGY Page 19
[Type the document title]
Python code to illustrate creating a tuple
student_data = (1, 'Rama', '2nd Year', 'CSE', 85.80)
print(type(student_data))
print(student_data)
When we run the above code, it produces the output as follows.
In Python, a tuple can also be created using tuple( ) constructor. The tuple()
constructor takes only one argument.
Syntax
tuple_name = tuple((element_1, element_2, element_3, ...))
CMR INSTITUTE OF TECHNOLOGY Page 20
[Type the document title]
For example, consider the following code for creating a tuple using tuple()
constructor which stores the details of a college.
Python code to illustrate creating a tuple using tuple() constructor.
college_info = tuple(('JNTUH', 'MRIT', 'MLTM'))
print(type(college_info))
print(college_info)
When we run the above code, it produces the output as follows.
CMR INSTITUTE OF TECHNOLOGY Page 21
[Type the document title]
Accessing Elements of a tuple in Python
In Python, the tuple elements are organized using index values that start with '0'
(zero) at first element and ends with 'length of the tuple - 1' at last element. The
individual elements of a tuple are accessed using the index values.
Syntax
tuple_name[index]
For example, consider the following code for accessing individual elements of a
tuple.
Python code to illustrate accessing elements of a tuple.
student_data = (1, 'Rama', '2nd Year', 'CSE', 85.80)
print(type(student_data))
print(f'Roll Number: {student_data[0]}\n'
f'Name of the Student: {student_data[1]}\n'
f'Branch: {student_data[3]}\n'
f'Year: {student_data[2]}\n'
f'Percentage: {student_data[4]}')
When we run the above code, it produces the output as follows.
CMR INSTITUTE OF TECHNOLOGY Page 22
[Type the document title]
In Python, we can also access a subset of elements from a tuple using slicing. We
can access any subset of elements from the specified starting index to ending
index. In tuple slicing, the default starting index is '0' and the default ending index
is 'length of the tuple - 1'.
Syntax
tuple_name[starting_index : ending_index]
For example, consider the following code for accessing a subset of elements from a
tuple.
Python code to illustrate accessing a subset of elements from a tuple.
student_data = (1, 'Rama', '2nd Year', 'CSE', 85.80)
print(student_data[2:4]) # Accessing elements from index 2 to 3
print(student_data[:4]) # Accessing elements from index 0 to 3
print(student_data[2:]) # Accessing elements from index 2 to the last element
CMR INSTITUTE OF TECHNOLOGY Page 23
[Type the document title]
When we run the above code, it produces the output as follows.
Changing an Element of a tuple in Python
In Python, the elements of a tuple are immutable. So, modification of individual
elements in a tuple is not allowed.
In Python, the whole tuple is mutable. So, we can modify or redefine the
entire tuple.
CMR INSTITUTE OF TECHNOLOGY Page 24
[Type the document title]
Looping through a tuple in Python
In Python, we can loop through a tuple using for statement with membership
operator in.
For example, consider the following code to loop through a tuple.
Python code to illustrate loop through a tuple.
student_data = (1, 'Rama', '2nd Year', 'CSE', 85.80)
for element in student_data:
print(f'Element from the tuple is - {element}')
When we run the above code, it produces the output as follows.
CMR INSTITUTE OF TECHNOLOGY Page 25
[Type the document title]
Finding the length of a tuple in Python
The Python provides a built-in function len( ) to find the length of a tuple. Here,
the length of a tuple is the total number of elements in that tuple.
For example, consider the following code to find the length of a tuple.
Python code to illustrate the length of a tuple.
student_data = (1, 'Rama', '2nd Year', 'CSE', 85.80)
tuple_length = len(student_data)
print(f'Length of the tuple {student_data} is {tuple_length}')
When we run the above code, it produces the output as follows.
CMR INSTITUTE OF TECHNOLOGY Page 26
[Type the document title]
Adding an element to the tuple in Python
Adding an element to the existing tuple in Python is not allowed.
Removing elements from a tuple in Python
In Python, removing an individual element from the existing tuple is not allowed.
However, the entire tuple can be deleted using del keyword.
For example, consider the following code.
Python code to illustrate del keyword using with a tuple.
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9)
print(f'The tuple is - {my_tuple}')
del my_tuple
print(f'The tuple after del keyword is used - {my_tuple}') # GENERATES ERROR
When we run the above code, it produces the output as follows.
CMR INSTITUTE OF TECHNOLOGY Page 27
[Type the document title]
Counting the number of time a value appears in the tuple
The Python provides a built-in method called count(value) to count the number of
times the given value appears in the tuple.
For example, consider the following code.
Python code to illustrate the count( ) method in a tuple.
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 5, 2)
print(f'The tuple is - {my_tuple}')
print(f'The value 2 appears {my_tuple.count(2)} times in the tuple.')
When we run the above code, it produces the output as follows.
CMR INSTITUTE OF TECHNOLOGY Page 28
[Type the document title]
Finding the index of a value in a tuple
The Python provides a built-in method called index( value ) to find the index of
that value in the tuple. If the given value not found in the tuple, then the execution
terminates with an error message ValueError: <<value>> is not in a tuple. For
example, consider the following example.
Python code to illustrate the index( ) method in a tuple.
my_tuple = (1, 2, 3, 4, 5)
print(f'The index of the value 4 is {my_tuple.index(4)}')
print(f'The index of the value 7 is {my_tuple.index(7)}') # generates an error
When we run the above code, it produces the output as follows.
CMR INSTITUTE OF TECHNOLOGY Page 29
[Type the document title]
Finding the Maximum and Minimum value in a tuple
The Python programming language provides built-in methods max( ) and min( ) to
find the maximum and minimum elements in a tuple.
For example, consider the following code.
Python code to illustrate the max( ) and mim( ) methods in a tuple.
my_tuple = (12, 2, 5, 90, 30, 40, 3)
print(f'The maximum value in the tuple is - {max(my_tuple)}')
print(f'The minimum value in the tuple is - {min(my_tuple)}')
When we run the above code, it produces the output as follows.
CMR INSTITUTE OF TECHNOLOGY Page 30
[Type the document title]
Sorting the elements of a tuple in Python
The Python provides a built-in method sorted( ) to sort all the elements of a tuple.
The method sorted( ) returns None. The sorted( ) method arranges the tuple
elements in increasing order by default. To sort the elements in decreasing order,
we need to pass an argument reverse = True to sorted( ) method.
For example, consider the following code.
Python code to illustrate sort( ) in a tuple.
my_tuple = (12, 2, 5, 90, 30, 40, 3)
print(f'The tuple is - {my_tuple}')
result_tuple = sorted(my_tuple)
print(f'Increasing order of the tuple is - {result_tuple}')
result_tuple = sorted(my_tuple, reverse=True)
print(f'Decreasing order of the tuple is - {result_tuple}')
When we run the above code, it produces the output as follows.
In Python, the functions max( ), min( ), and sorted( ) can be used with tuple
only if the tuple contains all elements of numerical type.
CMR INSTITUTE OF TECHNOLOGY Page 31
[Type the document title]
Python Sets
In Python, a set is a collection of unordered and unindexed elements of different
data types. That means sets are similar to the lists and tuples. But, the elements of a
set are maintained without any index and random order. The elements are
immutable however set itself is mutable. That means the elements of a set can not
be modified whereas the entire set can be modified or redefined. In Python, the set
data type (data structure) has implemented with a class known as a set. All the
elements of a set must be enclosed in curly braces, and each element must be
separated with a comma symbol.
Creating a set in Python
The general syntax for creating a set in Python is as follows.
Syntax
set_name = {element_1, element_2, element_3, ...}
For example, consider the following code for creating a set which stores the details
of a student.
Python code to illustrate creating a set
student_data = {1, 'Rama', '2nd Year', 'CSE', 85.80}
print(type(student_data))
print(student_data)
CMR INSTITUTE OF TECHNOLOGY Page 32
[Type the document title]
When we run the above code, it produces the output as follows.
In Python, a set can also be created using the set( ) constructor. The set()
constructor takes only one argument.
Syntax
set_name = set((element_1, element_2, element_3, ...))
For example, consider the following code for creating a set using set() constructor
which stores the details of a college.
Python code to illustrate creating a set using set() constructor.
college_info = set(('JNTUH', 'MRIT', 'MLTM'))
print(type(college_info))
print(college_info)
CMR INSTITUTE OF TECHNOLOGY Page 33
[Type the document title]
When we run the above code, it produces the output as follows.
Accessing Elements of a set in Python
In Python, the set elements are organized without any index values. So, accessing
individual elements of a set is not allowed. However, we can access the entire set
using the name of the set.
For example, consider the following code for accessing the entire set using the
name of the set.
Python code to illustrate accessing the entire set.
my_set = {1, 50, 'raja', 100.99, 'Sam'}
print(type(my_set))
print(my_set)
CMR INSTITUTE OF TECHNOLOGY Page 34
[Type the document title]
When we run the above code, it produces the output as follows.
Changing an Element of a set in Python
In Python, the elements of a set are immutable. So, modification of individual
elements in a set is not allowed.
In Python, the whole set is mutable. So, we can modify or redefine the entire
set.
Looping through a set in Python
In Python, we can loop through a set using for statement with a membership
operator in.
For example, consider the following code to loop through a set.
Python code to illustrate loop through a set.
CMR INSTITUTE OF TECHNOLOGY Page 35
[Type the document title]
student_data = {1, 'Rama', '2nd Year', 'CSE', 85.80}
for element in student_data:
print(f'Element from the set is - {element}')
When we run the above code, it produces the output as follows.
Existence of an element in a set in Python
In Python, we can test whether an element is present in a set or not using a
membership operator 'in'.
For example, consider the following code to test the existence of an element in a
set.
Python code to illustrate the existence of an element in a set.
student_data = {1, 'Rama', '2nd Year', 'CSE', 85.80}
if 'CSE' in student_data:
print(f'CSE is found in the set {student_data}!!!')
else:
print(f'CSE is not found in the set {student_data}!!!')
CMR INSTITUTE OF TECHNOLOGY Page 36
[Type the document title]
When we run the above code, it produces the output as follows.
Finding the length of a set in Python
The Python provides a built-in function len( ) to find the length of a set. Here, the
length of a set is the total number of elements in that set.
For example, consider the following code to find the length of a set.
Python code to illustrate the length of a set.
student_data = {1, 'Rama', '2nd Year', 'CSE', 85.80}
tuple_length = len(student_data)
print(f'Length of the tuple {student_data} is {tuple_length}')
When we run the above code, it produces the output as follows.
CMR INSTITUTE OF TECHNOLOGY Page 37
[Type the document title]
Adding an element to the existing set in Python
Adding elements to the existing set in Python is performed using the following
built-in methods.
add( value ) - This method adds the given element to the existing set.
update( list_of_values ) - This method adds a given list of elements to the
existing set.
For example, consider the following code.
Python code to illustrate adding an element to a set.
my_set = {1, 2, 3, 4, 5, 6, 7, 8, 9}
print(f'The set is - {my_set}')
# Adding element using add() method
CMR INSTITUTE OF TECHNOLOGY Page 38
[Type the document title]
my_set.add(10)
print(f'The set after adding 10 is - {my_set}')
# Adding multiple elements using update() method
my_set.update([100, 200])
print(f'The set after adding 100 and 200 is - {my_set}')
Removing elements from a set in Python
In Python, removing an element from the existing tuple is performed using the
following built-in methods.
discard( value ) - This method removes the given element from the set. This
method returns a None value. When the given element is not found in the
set, then it simply ignores it but does not cause any error.
remove( value ) - This method removes the given element from the set. This
method returns a None value. When the given element is not found in the
set, then it causes an error.
pop( ) - This method removes the last element from the set. This method
returns the removed value. As the set is an unordered sequence of elements,
so we will not know what element that gets removed.
clear( ) - This method removes all the elements from the set. That means the
clear( ) method make the set empty. This method returns the None value.
CMR INSTITUTE OF TECHNOLOGY Page 39
[Type the document title]
del keyword - This keyword deletes the set completely. Once the del
keyword has used on a set, we can not access it in the rest of the code.
For example, consider the following code.
Python code to illustrate remove operations in a set.
my_set = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
print(f'The set is - {my_set}')
my_set.discard(5)
my_set.discard(50)
print(f'The set after discarding 5 is {my_set}')
my_set.remove(3)
# my_set.remove(30) # Generates an error
print(f'The set after removing 3 is {my_set}')
my_set.pop()
print(f'The set after pop is {my_set}')
my_set.clear()
print(f'The set after clear is {my_set}')
del my_set
# print(f'The set after del is {my_set}') # Generates an error
When we run the above code, it produces the output as follows.
CMR INSTITUTE OF TECHNOLOGY Page 40
[Type the document title]
Finding Maximum and Minimum value in a tuple
The Python programming language provides built-in methods max( ) and min( ) to
find the maximum and minimum elements in a set.
For example, consider the following code.
Python code to illustrate max( ) and mim( ) methods in a set.
my_set = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 4}
print(f'The set is - {my_set}')
print(f'The maximum element is - {max(my_set)}')
print(f'The minimum element is - {min(my_set)}')
CMR INSTITUTE OF TECHNOLOGY Page 41
[Type the document title]
When we run the above code, it produces the output as follows.
Sorting the elements of a set in Python
The Python provides a built-in method sorted( ) to sort all the elements of a set.
The method sorted( ) returns a list of the element in sorted order. The sorted( )
method arranges the set elements in increasing order by default. To sort the
elements in decreasing order, we need to pass an argument reverse = True to
sorted( ) method.
For example, consider the following code.
Python code to illustrate sort( ) in a set.
my_set = {1, 2, 3, 42, 50, 6, 7, 8, 9, 10, 4}
print(f'The set is - {my_set}')
CMR INSTITUTE OF TECHNOLOGY Page 42
[Type the document title]
my_set = sorted(my_set)
print(f'The sorted elements (increasing order) of set is {my_set}')
my_set = sorted(my_set, reverse=True)
print(f'The sorted elements (decreasing order) of set is {my_set}')
When we run the above code, it produces the output as follows.
In Python, the functions max( ), min( ), and sorted( ) can be used with the
set only if the set contains all elements of numerical type.
Union of sets in Python
The Python provides the following ways to perform union of two or more number
of sets.
union( ) - union( ) is a built-in method used to perform a union of two or
more number of sets.
Operator '|' - This operator is used to perform a union of two or more
number of sets.
For example, consider the following code.
CMR INSTITUTE OF TECHNOLOGY Page 43
[Type the document title]
Python code to illustrate the union of sets.
my_set_1 = {1, 2, 3, 4, 5, 100, 4}
my_set_2 = {10, 3, 'Raja', 4, 100}
my_set_3 = {1000, 3, 'Rama', 14, 10000, 5}
# Union operation using method union()
print(my_set_1.union(my_set_2, my_set_3))
# Union operation using operator |
print(my_set_1 | my_set_2 | my_set_3)
When we run the above code, it produces the output as follows.
The intersection of sets in Python
The Python provides the following ways to perform an intersection of two or more
number of sets.
intersection( ) - intersection( ) is a built-in method used to perform
intersection of two or more number of sets.
Operator '&' - This operator is used to perform the intersection of two or
more number of sets.
CMR INSTITUTE OF TECHNOLOGY Page 44
[Type the document title]
For example, consider the following code.
Python code to illustrate the intersection of sets.
my_set_1 = {1, 2, 3, 4, 5, 100, 4}
my_set_2 = {10, 3, 'Raja', 4, 100}
# Intersection using method intersection()
print([Link](my_set_1, my_set_2))
# Intersection using operator &
print(my_set_1 & my_set_2)
When we run the above code, it produces the output as follows.
The difference of sets in Python
The Python provides the following ways to perform the difference operation of two
or more number of sets. The difference operation on sets is the results with a set
which contains the elements from the first operand set those are not in the second
operand set.
CMR INSTITUTE OF TECHNOLOGY Page 45
[Type the document title]
difference( ) - difference( ) is a built-in method used to perform difference
of two or more number of sets.
Operator '-' - This operator is used to perform a difference of two or more
number of sets.
For example, consider the following code.
Python code to illustrate the difference of sets.
my_set_1 = {1, 2, 3, 4, 5, 100, 4}
my_set_2 = {10, 3, 'Raja', 4, 100}
# Difference operation using difference()
print([Link](my_set_1, my_set_2))
# Difference operation using operator -
print(my_set_1 - my_set_2)
When we run the above code, it produces the output as follows.
CMR INSTITUTE OF TECHNOLOGY Page 46
[Type the document title]
Symmetric difference of sets in Python
The Python provides the following ways to perform the symmetric difference
operation of two or more number of sets. The symmetric difference operation on
sets is the results with a set which contains the elements from all the operand sets
but the common elements from all the sets are not included.
symmetric_difference( ) - The symmetric_difference( ) is a built-in method
used to perform symmetric difference operation of two or more number of
sets.
Operator '^' - This operator is used to perform a symmetric difference of
two or more number of sets.
For example, consider the following code.
CMR INSTITUTE OF TECHNOLOGY Page 47
[Type the document title]
Python code to illustrate the symmetric difference of sets.
my_set_1 = {1, 2, 3, 4, 5, 100, 4}
my_set_2 = {10, 3, 'Raja', 4, 100}
# Symmetric difference operation using difference()
print(set.symmetric_difference(my_set_1, my_set_2))
# Symmetric difference operation using operator -
print(my_set_1 ^ my_set_2)
When we run the above code, it produces the output as follows.
CMR INSTITUTE OF TECHNOLOGY Page 48
[Type the document title]
Python Dictionary
In Python, a dictionary is a collection of elements where each element is a pair of
key and value. In Python, the dictionary data type (data structure) has implemented
with a class known as dict. All the elements of a dictionary must be enclosed in
curly braces, each element must be separated with a comma symbol, and every pair
of key and value must be separated with colon ( : ) symbol.
Creating a dictionary in Python
The general syntax for creating a dictionary in Python is as follows.
Syntax
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3, ...}
For example, consider the following code for creating a dictionary which stores the
details of a student.
CMR INSTITUTE OF TECHNOLOGY Page 49
[Type the document title]
Python code to illustrate creating a dictionary
student_dictionary = {'rollNo': 1, 'name': 'Raja', 'department': 'CSE', 'year': 2}
print(type(student_dictionary))
When we run the above code, it produces the output as follows.
In Python, a dictionary can also be created using the dictionary( ) constructor. The
dictionary() constructor takes only one argument.
Syntax
dictionary_name = dict({key_1: value_1, key_2: value_2, key_3: value_3, ...})
For example, consider the following code for creating a dictionary using
dictionary() constructor which stores the details of a college.
Python code to illustrate creating a dictionary using dict() constructor.
student_dictionary = dict({'rollNo': 1, 'name': 'Raja', 'department': 'CSE', 'year': 2})
CMR INSTITUTE OF TECHNOLOGY Page 50
[Type the document title]
print(type(student_dictionary))
When we run the above code, it produces the output as follows.
Accessing Elements of a dictionary in Python
In Python, the dictionary elements are organized based on the keys. So, we can
access using the key of a value in the dictionary. The Python provides the
following ways to access the elements of a dictionary.
Using Key as index - The elements of a dictionary can be accessed using
the key as an index.
CMR INSTITUTE OF TECHNOLOGY Page 51
[Type the document title]
Example
print(student_dictionary[name])
get( key ) - This method returns the value associated with the given key in
the dictionary.
Example
print(student_dictionary.get('name'))
Accessing the whole dictionary - In Python, we use the name of the
dictionary to access the whole dictionary.
Example
print(student_dictionary)
items( ) - This is a built-in method used to access all the elements of a
dictionary in the form of a list of key-value pair.
Example
print(student_dictionary.items())
keys( ) - This is a built-in method used to access all the keys in a dictionary
in the form of a list.
Example
print(student_dictionary.keys())
values( ) - This is a built-in method used to access all the values in a
dictionary in the form of a list.
Example
print(student_dictionary.values())
For example, consider the following code for accessing the elements of a
dictionary.
Python code to illustrate accessing elements in a dictionary.
student_dictionary = {'rollNo': 1, 'name': 'Raja', 'department': 'CSE', 'year': 2}
print(type(student_dictionary))
print(student_dictionary['rollNo']) # Accessing using key as index
CMR INSTITUTE OF TECHNOLOGY Page 52
[Type the document title]
print(student_dictionary.get('name')) # Accessing using get() method
print(student_dictionary) # Accessing whole dictionary using the name of the
dictionary
print(student_dictionary.items()) # Accessing all elements of a dictionary using
items() method
print(student_dictionary.keys()) # Accessing all keys in a dictionary using keys()
method
print(student_dictionary.values()) # Accessing all value in a dictionary using
values() method
When we run the above code, it produces the output as follows.
Changing an Element of a dictionary in Python
In Python, the value of a specific element in a dictionary can be changed using the
respective key as an index. The following example shows changing the name to
'Seetha'.
Python code to illustrate loop through a set.
student_dictionary = {'rollNo': 1, 'name': 'Raja', 'department': 'CSE', 'year': 2}
print(f'Dictionary is {student_dictionary}')
student_dictionary['name'] = 'Seetha'
CMR INSTITUTE OF TECHNOLOGY Page 53
[Type the document title]
print(f'Dictionary after changing name to Seetha is - {student_dictionary}')
When we run the above code, it produces the output as follows.
Looping through a dictionary in Python
In Python, we can loop through a dictionary using for statement with a
membership operator in.
For example, consider the following code to loop through a dictionary.
Python code to illustrate loop through a dictionary.
student_dictionary = {'rollNo': 1, 'name': 'Raja', 'department': 'CSE', 'year': 2}
print(f'Dictionary is {student_dictionary}')
for every_key in student_dictionary:
print(f'{every_key} --> {student_dictionary[every_key]}')
When we run the above code, it produces the output as follows.
CMR INSTITUTE OF TECHNOLOGY Page 54
[Type the document title]
Existence of an element in a dictionary in Python
In Python, we can test whether an element is present in a dictionary or not using a
membership operator 'in'.
For example, consider the following code to test the existence of an element in a
dictionary.
Python code to illustrate the existence of an element in a dictionary.
student_dictionary = {'rollNo': 1, 'name': 'Raja', 'department': 'CSE', 'year': 2}
print(f'Dictionary is {student_dictionary}')
if 'Raja' in student_dictionary.values():
print(f'the value Raja is found in the dictionary {student_dictionary}')
else:
print(f'the value Raja is not found in the dictionary {student_dictionary}')
When we run the above code, it produces the output as follows.
CMR INSTITUTE OF TECHNOLOGY Page 55
[Type the document title]
Finding the length of a dictionary in Python
The Python provides a built-in function len( ) to find the length of a dictionary.
Here, the length of a dictionary is the total number of elements in that dictionary.
For example, consider the following code to find the length of a dictionary.
Python code to illustrate the length of a dictionary.
student_dictionary = {'rollNo': 1, 'name': 'Raja', 'department': 'CSE', 'year': 2}
print(f'Dictionary is {student_dictionary}')
print(f'Length of the dictionary is {len(student_dictionary)}')
When we run the above code, it produces the output as follows.
CMR INSTITUTE OF TECHNOLOGY Page 56
[Type the document title]
Adding an element to an existing dictionary in Python
Adding a new element to the existing dictionary is done by using a new key index
and assigning a value to it.
Adding a new element to the existing dictionary is also performed using a built-in
method update( key, value )
For example, consider the following code.
Python code to illustrate adding an element to a dictionary.
student_dictionary = {'rollNo': 1, 'name': 'Raja', 'department': 'CSE', 'year': 2}
print(f'Dictionary is {student_dictionary}')
student_dictionary['section'] = 'A' # Adding using new key assigned with a value
print(f'Dictionary after adding new element is\n{student_dictionary}')
student_dictionary.update({'percentage': 89.5}) # Adding using update() method
print(f'Dictionary after updated with new element is\n{student_dictionary}')
CMR INSTITUTE OF TECHNOLOGY Page 57
[Type the document title]
When we run the above code, it produces the output as follows.
Removing elements from a dictionary in Python
In Python, removing an element from the existing dictionary is performed using
the following built-in methods.
pop( key ) - This method removes the element with a specified key from the
dictionary.
popitem( ) - This method removes the last element from the dictionary.
clear( ) - This method removes all the elements from the dictionary. That
means the clear( ) method make the dictionary empty. This method returns
the None value.
del keyword with dict[key] - This keyword deletes the element with the
specified key from the dictionary. Once the del keyword has used on a
dictionary, we can not access it in the rest of the code.
del keyword - This keyword deletes the dictionary completely. Once the del
keyword has used on a dictionary, we can not access it in the rest of the
code.
For example, consider the following code.
CMR INSTITUTE OF TECHNOLOGY Page 58
[Type the document title]
Python code to illustrate remove operations in a dictionary.
student_dictionary = {'rollNo': 1, 'name': 'Raja', 'department': 'CSE',
'year': 2, 'section': 'A', 'percentage': 80.5}
print(f'Dictionary is {student_dictionary}')
student_dictionary.pop('year')
print(f'Thedictionary after removing element with kay year:\
n{student_dictionary}')
student_dictionary.popitem()
print(f'The dictionary after popitem():\n{student_dictionary}')
del student_dictionary['section']
print(f'The dictionary after deleting section:\n{student_dictionary}')
student_dictionary.clear()
print(f'The dictionary after clear:\n{student_dictionary}')
del student_dictionary
# print(f'The dictionary after del:\n{student_dictionary}') # Generates an error
When we run the above code, it produces the output as follows.
CMR INSTITUTE OF TECHNOLOGY Page 59
[Type the document title]
CMR INSTITUTE OF TECHNOLOGY Page 60
[Type the document title]
Python Class and Object
The Python is an object-oriented programming language from its beginning.
Almost everything in Python implemented using object concept. The Python
support all the features of OOP.
A class is a "blueprint" or "prototype" to define an object. Every object has its
properties and methods. That means a class contains some properties and methods.
Creating Class
In Python, we use the keyword class to create a class. The general class definition
looks like the following.
Syntax
class ClassName:
'Docstring - An optional documentation string'
statement_1
statement_2
...
statement_n
In the above syntax, the class is the keyword used to define a
class. ClassName can be any user-defined name but we must obey the naming
rules. The Docstring is an optional documentation string used to describe the class.
And the statement can be any statement.
The docstring of a class is accessed using ClassName.__doc__.
CMR INSTITUTE OF TECHNOLOGY Page 61
[Type the document title]
The class may contain attributes like data members (variables), code members
(methods), and also any Python statements. When a class contains Python
statements directly (means they do not belong to any method), they will be
executed normally in the class.
Creating Object
An object is a variable of class type. An object of a class is also known as an
instance of a class. All the members of a class are accessed using an object of that
class. We use the following syntax to create an object.
Syntax
object_name = ClassName(arguments)
Consider the following example.
Example
class Sample:
'This is a Docstring of sample class'
variable_a = 10
def sample_function(self):
print(f'This is sample function')
print('This statement does not belong to any method!')
obj = Sample()
obj.sample_function()
print(f'Accessing data member - a = {Sample.variable_a}')
When we run the above example code, it produces the following output.
CMR INSTITUTE OF TECHNOLOGY Page 62
[Type the document title]
In the above example, we have created a class called Sample with a data member
(a), a member function (sample_function()), and a Python statement. We also
created an object (obj) of the Sample class.
Accessing Class Members
In Python, we use a dot (.) operator to access the members of a class. In the above
example, we have used the following statements to access the sample_function()
member function and a data member of Sample class.
Example
CMR INSTITUTE OF TECHNOLOGY Page 63
[Type the document title]
obj.sample_function()
print(f'Accessing data member - a = {Sample.variable_a}')
In Python, the data members of a class need not be declared like local variables.
We can add, modify, and delete data members at any time.
In the above example, there is only one data member (variable_a) but we can add
new data members to the class at any time. A new data member is added to the
class when it is assigned with a value. Let's add a new data member
called variable_b. The following code adds variable_b to the class Sample.
Example
obj.variable_b = 100
print(f'Newly added data member variable_b = {obj.variable_b}')
In Python, the member functions must define in the class. We can't add member
functions later.
Members Objects
In Python, we can create an object of a member function. The same object is used
to call the member function. The following code creates an object method_obj for
the member function sample_function(), and it is called used the same object.
Example
method_obj = obj.sample_function()
method_obj()
CMR INSTITUTE OF TECHNOLOGY Page 64
[Type the document title]
self Parameter
In Python, every method of a class must have the first parameter as self. Here,
the self parameter refers to the current object being used to call that method.
However, it does not have to be named self, we can call it whatever we like, but it
has to be the first parameter of any function in the class.
Consider the following example code.
Example
class Sample:
i = 10
def __init__(self, x):
self.x = x
def myFun_1(self):
print(f'This if myFun_1 and self.x = {self.x}')
def myFun_2(xyz): # Here xyz is used instead of self
print(f'This if myFun_2 and xyz.x = {xyz.x}')
obj = Sample(10)
obj.myFun_1()
obj.myFun_2()
In the above example, the method myFun_1() has defined with self parameter and
the method myFun_2() has defined with xyz. Here both the parameters refer to the
current object being used to call the corresponding method.
CMR INSTITUTE OF TECHNOLOGY Page 65
[Type the document title]
When we run the above example code, it produces the following output.
CMR INSTITUTE OF TECHNOLOGY Page 66
[Type the document title]
Python Constructor
The Python is an object-oriented programming language from its beginning.
Almost everything in Python implemented using object concept. The Python
support all the features of OOP.
In Python, the class may contain data members, member functions (methods), and
Python statements. Every class in Python has a special method __init__( ) which
executes on every object creation of that class.
A constructor is a special method or member function of a class which
automatically gets executes on every object creation.
There are two types of constructors and they are as follows.
Constructor without parameters (or) Default Constructor
Constructor with parameters (or) Parameterized Constructor
Default Constructor is a constructor without any parameters, however, it has a
default parameter self.
Parameterized Constructor is a constructor with one or more parameters. A
parameterized constructor may have any number of parameters.
Creating Default Constructor
In Python, the constructor is created using a special method called __init__( ). In
programming languages like C++, Java, etc. the constructor has the same name as
the class name, but in Python, every class has the constructor with same name
__init__( ).
CMR INSTITUTE OF TECHNOLOGY Page 67
[Type the document title]
Example
class Sample:
i = 10
def __init__(self):
self.i = 100
print(f'Object has created!')
print(f'Data member "i" is initialized with {self.i}.')
obj = Sample()
When we run the above example code, it produces the following output.
When the user does not define any constructor, the compiler automatically creates
a default constructor.
In Python, a class can have only one constructor. Constructor overloading is not
allowed in Python.
CMR INSTITUTE OF TECHNOLOGY Page 68
[Type the document title]
Creating Parameterized Constructor
In Python, a constructor may have any number of parameters. The following code
illustrates how parameterized constructor is created.
Example
class Sample:
i = 10
def __init__(self, value):
self.i = value
print(f'Object has created!')
print(f'Data member "i" is initialized with {self.i}.')
obj = Sample(1000)
When we run the above example code, it produces the following output.
CMR INSTITUTE OF TECHNOLOGY Page 69
[Type the document title]
Points to be Remembered!
In Python, the method __init__( ) is called as constructor but it does not
creates an object instead it instatiates the object. To create an object, Python
uses a special method __new__( ). When a class has both __init__( ) and
__new__( ) methods, the __new__( ) method overrides __init__( ) method.
In Python, actually both __new__( ) and __init__( ) together forms a
constructor.
The __new__( ) method is used to create an object.
The __init__( ) method is used to instantiate an object.
CMR INSTITUTE OF TECHNOLOGY Page 70
[Type the document title]
Python Inheritance
The inheritance is a very useful and powerful concept of object-oriented
programming. Using the inheritance concept, we can use the existing features of
one class in another class.
The inheritance is the process of acquiring the properties of one class to
another class.
In inheritance, we use the terms like parent class, child class, base class, derived
class, superclass, and subclass.
The Parent class is the class which provides features to another class. The parent
class is also known as Base class or Superclass.
The Child class is the class which receives features from another class. The child
class is also known as the Derived Class or Subclass.
In the inheritance, the child class acquires the features from its parent class. But the
parent class never acquires the features from its child class.
There are five types of inheritances, and they are as follows.
Simple Inheritance (or) Single Inheritance
Multiple Inheritance
Multi-Level Inheritance
Hierarchical Inheritance
Hybrid Inheritance
CMR INSTITUTE OF TECHNOLOGY Page 71
[Type the document title]
The following picture illustrates how various inheritances are implemented.
CMR INSTITUTE OF TECHNOLOGY Page 72
[Type the document title]
Creating a Child Class
In Python, we use the following general structure to create a child class from a
parent class.
Syntax
class ChildClassName(ParentClassName):
ChildClass implementation
Let's look at individual inheritance type with an example.
Simple Inheritance (or) Single Inheritance
In this type of inheritance, one child class derives from one parent class. Look at
the following example code.
Example
class ParentClass:
def feature_1(self):
print('feature_1 from ParentClass is running...')
def feature_2(self):
print('feature_2 from ParentClass is running...')
class ChildClass(ParentClass):
CMR INSTITUTE OF TECHNOLOGY Page 73
[Type the document title]
def feature_3(self):
print('feature_3 from ChildClass is running...')
obj = ChildClass()
obj.feature_1()
obj.feature_2()
obj.feature_3()
When we run the above example code, it produces the following output.
CMR INSTITUTE OF TECHNOLOGY Page 74
[Type the document title]
Multiple Inheritance
In this type of inheritance, one child class derives from two or more parent classes.
Look at the following example code.
Example
class ParentClass_1:
def feature_1(self):
print('feature_1 from ParentClass_1 is running...')
class ParentClass_2:
def feature_2(self):
print('feature_2 from ParentClass_2 is running...')
class ChildClass(ParentClass_1, ParentClass_2):
def feature_3(self):
print('feature_3 from ChildClass is running...')
obj = ChildClass()
obj.feature_1()
obj.feature_2()
obj.feature_3()
CMR INSTITUTE OF TECHNOLOGY Page 75
[Type the document title]
When we run the above example code, it produces the following output.
Multi-Level Inheritance
In this type of inheritance, the child class derives from a class which already
derived from another class. Look at the following example code.
Example
class ParentClass:
def feature_1(self):
print('feature_1 from ParentClass is running...')
CMR INSTITUTE OF TECHNOLOGY Page 76
[Type the document title]
class ChildClass_1(ParentClass):
def feature_2(self):
print('feature_2 from ChildClass_1 is running...')
class ChildClass_2(ChildClass_1):
def feature_3(self):
print('feature_3 from ChildClass_2 is running...')
obj = ChildClass_2()
obj.feature_1()
obj.feature_2()
obj.feature_3()
When we run the above example code, it produces the following output.
CMR INSTITUTE OF TECHNOLOGY Page 77
[Type the document title]
Hierarchical Inheritance
In this type of inheritance, two or more child classes derive from one parent class.
Look at the following example code.
Example
class ParentClass_1:
def feature_1(self):
print('feature_1 from ParentClass_1 is running...')
class ParentClass_2:
def feature_2(self):
print('feature_2 from ParentClass_2 is running...')
class ChildClass(ParentClass_1, ParentClass_2):
def feature_3(self):
print('feature_3 from ChildClass is running...')
obj = ChildClass()
obj.feature_1()
obj.feature_2()
obj.feature_3()
When we run the above example code, it produces the following output.
CMR INSTITUTE OF TECHNOLOGY Page 78
[Type the document title]
Hybrid Inheritance
The hybrid inheritance is the combination of more than one type of inheritance.
We may use any combination as a single with multiple inheritances, multi-level
with multiple inheritances, etc.,
CMR INSTITUTE OF TECHNOLOGY Page 79