0% found this document useful (0 votes)
43 views72 pages

UNIT III

The document discusses lists in Python including creating and initializing lists, basic list operations like indexing, slicing, concatenation and membership checking. It also covers list methods, traversing lists using loops, and some important built-in list functions.

Uploaded by

Upendra Neravati
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views72 pages

UNIT III

The document discusses lists in Python including creating and initializing lists, basic list operations like indexing, slicing, concatenation and membership checking. It also covers list methods, traversing lists using loops, and some important built-in list functions.

Uploaded by

Upendra Neravati
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 72

RGM College of Engineering & Technology (Autonomous), Nandyal

UNIT-III
DATA STRUCTURES
SYLLABUS
* Lists: Operations on List, important methods used on list. List comprehensions

LIST
* List is a collection of items (Python objects)
* The purpose of the list is, to group up the things, which fall under the same category
Examples
* List of grocery items,
* List of employee ids,
* List of book names
* Names of all students
* Roll numbers of all students
* Mobile numbers of all students etc..,
Creating a list in python is putting different comma-separated-values, between square brackets.
Characteristics
* List maintains the order of data insertion
* Lists are mutable, i.e., we can modify the elements
* Even though the list principle suggests homogeneous data items in it, it is not mandatory and still
allowed to have different types (Heterogeneous data) which makes it a most powerful tool in Python

Department of Mechanical Engineering


1
RGM College of Engineering & Technology (Autonomous), Nandyal

* List allows duplicates


* Growable in nature, i.e based on our requirement we can increase or decrease the size.
Applications:
* If the content is keep on changing, better to opt for list type. For example, Youtube comments or
Facebook comments or Udemy reviews (which are keep on changing day by day).
* Used in JSON (Java Script Object Notation) format to transmit data between web applciation and
server.
* Used in Databases
* Used in array operations

BASIC LIST OPERATIONS


* Create a list: Create a comma separated list of elements and assign to variable.
* Indexing: Accessing the list items.
* Slicing : accessing the part of the list elements.
* Concatenation: adding the lists
* Updating : Updating the list elements
* Membership: To check the membership of element.
* Comparison
* Repetition

1. We can create empty list object as follows...


list = []
print(list)
print(type(list))
[]
<class 'list'>
2.If we know elements already then we can create list as follows
list = [10,20,30,40]
print(list)
print(type(list))
[10, 20, 30, 40]
<class 'list'>

Department of Mechanical Engineering


2
RGM College of Engineering & Technology (Autonomous), Nandyal

3. With dynamic input:


list=input("Enter List:") # Entire input is considered as string
print(list)
print(type(list))
Enter List:10, 'mech', 30
10, 'mech', 30
<class 'str'>
list = eval(input("Enter List:"))
print(list)
print(type(list))
Enter List:[10, 'mech', 30]
[10, 'mech', 30]
<class 'list'>
4. With list() function:
l=list(range(0,10,2))
print(l)
[0, 2, 4, 6, 8]
5. With split() function:
s="Learning Python is very very easy !!!"
l=s.split()
print(l)
print(type(l))
['Learning', 'Python', 'is', 'very', 'very', 'easy', '!!!']
<class 'list'>
Note:
Sometimes we can take list inside another list,such type of lists are called nested lists. [10, 20, [30, 40]]

Repetition Operator:The repetition operator enables the list elements to be repeated multiple times.
list_1 = [1, 2, 3, 4]
list_3 =list_1*3
print(list_3)
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
Concatenation:It concatenates the list mentioned on either side of the operator.
list_1 = [1, 2, 3, 4]
list_2= [5, 6, 7, 8]

Department of Mechanical Engineering


3
RGM College of Engineering & Technology (Autonomous), Nandyal

list_3 =list_1+list_2
print(list_3)
[1, 2, 3, 4, 5, 6, 7, 8]
Membership:It returns true if a particular item exists in a particular list otherwise false.
list_1 = [1, 2, 3, 4]
print(2 in list_1)
print(5 not in list_1)
True
True
Length: It is used to get the length of the list
list_1 = [1, 2, 3, 4]
len(list_1)
4
#Apply Relational Operator
list_1 = [1, 2, 3, 4]
list_2= [5, 6, 7, 8]
print(list_1 == list_2)
print(list_1 != list_2)
print(list_1>list_2)# it is based on the first element
print(list_1<list_2)
False
True
False
True
list_1 = [1, 2, 3, 4]
list_2= [1, 6, 7, 8]
print(list_1>list_2)
# it is based on the second element, if the first element in list is same
print(list_1<list_2)
print(list_1>=list_2)
print(list_1<=list_2)
False
True
False
True

Department of Mechanical Engineering


4
RGM College of Engineering & Technology (Autonomous), Nandyal

Updating
list = [1,4,8,9,13]
list[1] = 2
print(list)
[1, 2, 8, 9, 13]
ACCESSING ELEMETS OF LIST
* We can access elements of the list either by using index or by using slice operator(:)
* Indexing: Indexing is used to obtain individual elements. List follows zero based index. ie index of first
element is zero and supports both positive and negative indexing.
* Slicing: Slicing is used to obtain a sequence of elements.
1. By using Indexing
list=[10,20,30,40]
print(list[0]) #10
print(list[-1]) #40
print(list[-4]) #10
print(list[10]) #IndexError: list index out of range
10
40
10
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-33-714b2c12ce65> in <module>()
3 print(list[-1]) #40
4 print(list[-4]) #10
----> 5 print(list[10]) #IndexError: list index out of range

IndexError: list index out of range


list = [10,20,[30,40]]
print(list[2])
print(list[2][1])
[30, 40]
40
2. By using slice operator:
syntax: listname[start: stop: step]
l = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
print(l[0:4])
print(l[0: 5: 2])
print(l[:5]) # Taking/Returning n first elements of a list------l[:5] is equivalent to l[0:5]. This combination

Department of Mechanical Engineering


5
RGM College of Engineering & Technology (Autonomous), Nandyal

is a handy shortcut to take n first elements of a list.


print(l[-3:]) #Taking/Returning n last elements of a list
print(l[-3:8]) #We can freely mix negative and positive indexes in start and stop positions:
print(l[:-2])#Taking/Returning all but n last elements of a list
print(l[::2]) #Taking/Returning every nth-element of a list
print(l[1::2]) #Here we omit start/stop parameters and use only step. By providing start we can skip some
elements:
print(l[1:-3:2]) #And if we don’t want to include some elements at the end, we can also add the stop
parameter:
print(l[::-1]) #We can use a negative step to obtain a reversed list:
print(l[-2::-1]) #So, we start from the -2 element (value 90) and go from right to left collecting all the
elements in a reversed list.
[10, 20, 30, 40]
[10, 30, 50]
[10, 20, 30, 40, 50]
[80, 90, 100]
[80]
[10, 20, 30, 40, 50, 60, 70, 80]
[10, 30, 50, 70, 90]
[20, 40, 60, 80, 100]
[20, 40, 60]
[100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
[90, 80, 70, 60, 50, 40, 30, 20, 10]
List vs mutability:
#Substitute part of a list
l = [10,20,30,40,50,60, 70, 80, 90, 100]
l[:4] = [1,2,3,4]
print(l)
[1, 2, 3, 4, 50, 60, 70, 80, 90, 100]
#Replace Every n-th Element
l = [10,20,30,40,50,60, 70, 80, 90, 100]
l[::2] = [1,2,3,4,5]
print(l)
[1, 20, 2, 40, 3, 60, 4, 80, 5, 100]
Traversing the elements of List:
The sequential access of each element in the list is called traversal
#1. By using while loop:
n=[0,1,2,3,4,5,6,7,8,9,10]
i=0
while i<len(n):

Department of Mechanical Engineering


6
RGM College of Engineering & Technology (Autonomous), Nandyal

print(n[i])
i=i+1
0
1
2
3
4
5
6
7
8
9
10
#By using for loop:
list=[0,1,2,3,4,5,6,7,8,9,10]
for i in list:
print(i)
0
1
2
3
4
5
6
7
8
9
10
#To display only even numbers:
n=[0,1,2,3,4,5,6,7,8,9,10]
for n1 in n:
if n1%2==0:
print(n1)
0
2
4
6
8
10
#To display elements by index wise:
l=["A","B","C"]

Department of Mechanical Engineering


7
RGM College of Engineering & Technology (Autonomous), Nandyal

x=len(l)
for i in range(x):
print(l[i],"is available at positive index: ",i,"and at negative index: ",i-x)
A is available at positive index: 0 and at negative index: -3
B is available at positive index: 1 and at negative index: -2
C is available at positive index: 2 and at negative index: -1
Important functions of List:
What is the difference between function and method?
In Python you can use both these terms interchangeably.
* Function:
Function by default considered as method also.
If a function is declaring outside a class is called as function.
* Method :
If you are declaring a function inside a class is called as a method.
In other words, if you are calling any function with object reference is called as method.
Built-in list functions
* all(): Returns True if all the items in the list has a True value.
* any() : Returns True if even one item in the list has a True value.
* enumerate(): Returns an enumerate object consisting of the index and value of all items of list as a tuple
pair.
* len(): This function calculates the length i.e., the number elements in the list.
* list(): This function converts an iterable (tuple, string, set, dictionary) to a list
* max():
This function returns the item with the highest value from the list
* min()
This function returns the item with the lowest value from the list.
* sorted():
This function returns a sorted result of the list, with the original list unchanged.
* sum():

Department of Mechanical Engineering


8
RGM College of Engineering & Technology (Autonomous), Nandyal

This function returns the sum of all elements in the list.


This function works only on numeric values in the list and will error out if the list contains a mix of string
and numeric values.
Built-in list methods
* append(x):
Add a single item to the end of the list
* extend(iterable):
Extend the list with the items of another list or iterable
* insert(index, item):
Insert an item at a position before the element given by index.
* remove(element):
Remove the first item in the list whose value is element
Error if the item doesn't exist with the value element in list
* pop(), pop(index):
Removes an item at the given position specified by index
Removes and returns the last element if index is not specified
If an invalid index is specified, then an IndexError is thrown
* count(x):
Return the number of times the item x appears in the list
* sort(key = None, reverse = False):
Sort the items of the list in place in ascending order
If the parameter reverse = True, then the list is sorted in place in descending order
* reverse():
Reverse the order of elements of the list in place
* copy()
Return the shallow copy of the list
Equivalent to a[:]
The above functions and methods are grouped into 3 categories
I. To get information about list:
len(): returns the number of elements present in the list
count(): It returns the number of occurrences of specified item in the list.
index(): function: returns the index of first occurrence of the specified item

Department of Mechanical Engineering


9
RGM College of Engineering & Technology (Autonomous), Nandyal

n=[10,20,30,40]
print(len(n))
4
n=[1,2,2,2,2,3,3]
print(n.count(1))
print(n.count(2))
print(n.count(3))
print(n.count(4))
1
4
2
0
n=[1,2,2,2,2,3,3]
print(n.index(1)) # 0
print(n.index(2)) # 1
print(n.index(3)) # 5
print(n.index(4)) #If the specified element not present in the list then we will get ValueError.
0
1
5
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-7-7f09438192d2> in <module>()
3 print(n.index(2)) # 1
4 print(n.index(3)) # 5
----> 5 print(n.index(4)) #If the specified element not present in the list then we will get ValueError.

ValueError: 4 is not in list

Department of Mechanical Engineering


10
RGM College of Engineering & Technology (Autonomous), Nandyal

II. Manipulating Elements of List:


1. append() function:
We can use append() function to add new item (which can be any Python object, such as an Integer,
String, another List, Dictionary or anything else.) at the end of the existing python list.
* Syntax: list.append(item)
*append() function only takes a single argument that is the item which is needed to be added or appended
at the end of the list.
* append() Return Value: None
- Obviously, this method would not have anything to return, so it simply returns None.
list=[]
list.append("A")
list.append("B")
list.append("C")
print(list)
['A', 'B', 'C']
outdoor_games = ["Cricket","Football","Basketball","Hockey"]
indoor_games = ["Chess","Ludo","Snakes & Ladders"]
outdoor_games.append(indoor_games)
#Checking updated List
print(outdoor_games)
['Cricket', 'Football', 'Basketball', 'Hockey', ['Chess', 'Ludo', 'Snakes & Ladders']]
#Eg: To add all elements to list upto 100 which are divisible by 10
list=[]
for i in range(101):
if i%10==0:
list.append(i)
print(list)
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
#Another way
list= []
for i in range(0,101,10):
list.append(i)
print(list)
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Department of Mechanical Engineering


11
RGM College of Engineering & Technology (Autonomous), Nandyal

2. insert() function:
* The list.insert() method is used to insert an item at a particular index into a given Python List. The new
item to be inserted and the index at which it is to be inserted has to be provided as the second and first
arguments to this method respectively.
list.insert(index, item)
list=[1,2,3,4,5]
list.insert(1,888)
print(list)
[1, 888, 2, 3, 4, 5]
list=[1,2,3,4,5]
list.insert(10,777)
list.insert(-10,999)
print(list)
print(list.index(777))
print(list.index(999))
[999, 1, 2, 3, 4, 5, 777]
6
0
Note:
If the specified index is greater than max index, then element will be inserted at last position.
#If the specified index is smaller than min index, then element will be inserted at first position
#Example - Python List insert()
#A List with different collection objects
collections = [(1,2,3),[4,5,6],{7,8,9}]
print("Initial List:",collections)
#Inserting a new List Object at index 0
collections.insert(0,['A','B','C'])
print("Updated List:",collections)
#Inserting a new Set Object at index 2
collections.insert(2,{'D','E','F'})
print("Updated List:",collections)
#Inserting a new Tuple Object at index 4
collections.insert(4,('G','H','I'))
print("Updated List:",collections)
Initial List: [(1, 2, 3), [4, 5, 6], {8, 9, 7}]
Updated List: [['A', 'B', 'C'], (1, 2, 3), [4, 5, 6], {8, 9, 7}]
Updated List: [['A', 'B', 'C'], (1, 2, 3), {'D', 'E', 'F'}, [4, 5, 6], {8, 9, 7}]
Updated List: [['A', 'B', 'C'], (1, 2, 3), {'D', 'E', 'F'}, [4, 5, 6], ('G', 'H', 'I'), {8, 9, 7}]

Department of Mechanical Engineering


12
RGM College of Engineering & Technology (Autonomous), Nandyal

3. extend() function:
To add all items of one list to another list,we use extend() method.
list1.extend(list2)
order1=["Chicken","Mutton","Fish"]
order2=["RC","KF","FO"]
order1.extend(order2)
print(order1)
print(order2)
['Chicken', 'Mutton', 'Fish', 'RC', 'KF', 'FO']
['RC', 'KF', 'FO']
numbers_list = [1,2,3,4,5]
numbers_tuple = (6,7,8,9,10)
numbers_set = {11,12,13,14,15}
print("Original List",numbers_list)
#Extending List using tuple
numbers_list.extend(numbers_tuple)
print("Extended List:",numbers_list)
#Extending List using set
numbers_list.extend(numbers_set)
print("Extended List:",numbers_list)
Original List [1, 2, 3, 4, 5]
Extended List: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Extended List: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
order1=["Chicken","Mutton","Fish"]
order2=["RC","KF","FO"]
order3 = order1 + order2
print(order1)
print(order2)
print(order3)
['Chicken', 'Mutton', 'Fish']
['RC', 'KF', 'FO']
['Chicken', 'Mutton', 'Fish', 'RC', 'KF', 'FO']

Department of Mechanical Engineering


13
RGM College of Engineering & Technology (Autonomous), Nandyal

order=["Chicken","Mutton","Fish"]
order.extend("Mushroom") # It adds every character as a single element to the list
print(order)
['Chicken', 'Mutton', 'Fish', 'M', 'u', 's', 'h', 'r', 'o', 'o', 'm']
Explanation :
Here, 'Mushroom' is a string type, in this string 8 elements are there. These elements are added seperately.
numbers_list = [1,2,3,4,5]
numbers_list_2 = ["A","B","C","D","E"]
numbers_tuple = (6,7,8,9,10)
numbers_set = {11,12,13,14,15}
print("Original List",numbers_list)
#Concatenating numbers_list_2 into numbers_list
numbers_list = numbers_list + numbers_list_2
#OR
#numbers_list += numbers_list_2
#Extending List using tuple
numbers_list += numbers_tuple
print("Extended List:",numbers_list)
#Extending List using set
numbers_list += numbers_set
print("Extended List:",numbers_list)
Original List [1, 2, 3, 4, 5]
Extended List: [1, 2, 3, 4, 5, 'A', 'B', 'C', 'D', 'E', 6, 7, 8, 9, 10]
Extended List: [1, 2, 3, 4, 5, 'A', 'B', 'C', 'D', 'E', 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
4. remove() function:
We can use this function to remove specified item from the list.
If the item present multiple times then, only first occurrence will be removed
list.remove(itemToBeRemoved)
list=[10,20,10,30]
list.remove(10)
print(list)
[20, 10, 30]

Department of Mechanical Engineering


14
RGM College of Engineering & Technology (Autonomous), Nandyal

If the specified item not present in list then we will get ValueError
5. pop() function:
It removes and returns the last element of the list.
This is only function which manipulates list and returns some element.
* The pop() method of the Python List Object is used to remove any item from the list by using its index.
This method also returns the item so removed.
removedItem = list.pop(itemIndex)
list=[10,20,30,40]
print(list.pop())
print(list.pop())
print(list)
40
30
[10, 20]
#A Python List
items = ["Pen", "Whiteboard", "Tablet", "Smartphone", "Cleaner"]
#Removing the item at Index 2 i.e. "Tablet"
removedItem = items.pop(2)
#Printing the so returned Removed item
print("Removed Item:",removedItem)
#Negative Indexing Removals
#Another Python List
items = ["Laptop","Bottle","Stick","Speaker","Rubber"]
#Removing the 3rd Last item from the List
#i.e. "Stick"
#using Negative Index -3
removedItem = items.pop(-3)
print("Removed Item", removedItem)
Removed Item: Tablet
Removed Item Stick
numbers = [10, 23, 30, 42, 50, 55, 76]

#Passing Index Out of the Range of the List


#Will raise IndexError: pop index out of range
numbers.pop(8)
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-51-ff7624fa208d> in <module>()
3 #Passing Index Out of the Range of the List

Department of Mechanical Engineering


15
RGM College of Engineering & Technology (Autonomous), Nandyal

4 #Will raise IndexError: pop index out of range


----> 5 numbers.pop(8)

IndexError: pop index out of range


If the list is empty then pop() function raises IndexError
Note:
1. pop() is the only function which manipulates the list and returns some value
2. In general we can use append() and pop() functions to implement stack datastructure by using
list,which follows LIFO(Last In First Out) order.
3. In general we can use pop() function to remove last element of the list. But we can use to remove
elements based on index.
We can use pop() function in following ways:
n.pop(index)===>To remove and return element present at specified index.
n.pop()==>To remove and return last element of the list

III. Ordering elements of List:


1.reverse(): We can use to reverse() order of elements of list
list.reverse()
list=[10,20,30,40]
list.reverse()
print(list)
[40, 30, 20, 10]

Department of Mechanical Engineering


16
RGM College of Engineering & Technology (Autonomous), Nandyal

2. sort() function:
In list by default insertion order is preserved. If you want to sort the elements of list according to default
natural sorting order then we should go for sort() method.
* For numbers ==> default natural sorting order is Ascending Order
* For Strings ==> default natural sorting order is Alphabetical Order
* It is used to arrange the order of the items in either Ascending or Descending or in a custom order.
list.sort(key=keyFunction, reverse=True/False)
list=[20,5,15,10,0]
list.sort()
print(list)
[0, 5, 10, 15, 20]
s=["Dog","Banana","Cat","Apple"]
s.sort()
print(s)
['Apple', 'Banana', 'Cat', 'Dog']
Note:
To use sort() function, compulsory list should contain only homogeneous elements, otherwise we will get
TypeError.
list=[20,10,"A","B"]
list.sort()
print(list)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-15-c63e865af43d> in <module>()
1 list=[20,10,"A","B"]
----> 2 list.sort()
3 print(list)

TypeError: '<' not supported between instances of 'str' and 'int'


list=['20',"B",'10',"A"]
list.sort()
print(list)
['10', '20', 'A', 'B']

Department of Mechanical Engineering


17
RGM College of Engineering & Technology (Autonomous), Nandyal

How to sort the elements of list in reverse of default natural sorting order:
One Simple Way
list=[40,10,30,20]
list.sort()
print(list)
list.reverse()
print(list)
[10, 20, 30, 40]
[40, 30, 20, 10]
Alternate Way :
We can sort according to reverse of default natural sorting order by using reverse = True argument.
list=[40,10,30,20]
list.sort()
print(list) #[10,20,30,40]
list.sort(reverse=True) # Reverse Sort a list i.e. sorting the list in the Descending order, we just have to
specify the argument reverse of the method sort() as True
print(list) #[40,30,20,10]
list.sort(reverse=False)
print(list) #[10,20,30,40]
[10, 20, 30, 40]
[40, 30, 20, 10]
[10, 20, 30, 40]
s=["Dog","Banana","Cat","Apple"]
s.sort(reverse= True) # reverse of Alphabetical order
print(s)
['Dog', 'Cat', 'Banana', 'Apple']
In the below example, we have a list of some strings and each of these strings has a different length. So,
here we’re sorting the list according to the length of the strings in ascending as well as in the descending
order.
demo = ["aaaaa","aa","a","aaaaaa","aaaa","aaaaaaa","aaa"]
print("Initial Ordeer: " + str(demo))
demo.sort(key = len)
print("Small To Large: " + str(demo))
demo.sort(key = len, reverse = True)
print("Large To Small: " + str(demo))
Initial Ordeer: ['aaaaa', 'aa', 'a', 'aaaaaa', 'aaaa', 'aaaaaaa', 'aaa']
Small To Large: ['a', 'aa', 'aaa', 'aaaa', 'aaaaa', 'aaaaaa', 'aaaaaaa']
Large To Small: ['aaaaaaa', 'aaaaaa', 'aaaaa', 'aaaa', 'aaa', 'aa', 'a']

Department of Mechanical Engineering


18
RGM College of Engineering & Technology (Autonomous), Nandyal

Sorting is a Python List using Custom Logic


Here also we’ll make use fo the key argument but to this argument, we’ll provide our own defined custom
function containing the logic of sorting.
I’ve taken a Python List that contains tuples as the items. Each tuple contains 3 numbers. The list is now
sorted according to the ascending order of the sum of the numbers in each tuple item.
alist = [(12, 0, 9),(11, 1, 2), (12, 5, 3), (5, 3, 0), (3, 4, 8)]
print("Original Order: " + str(alist))
def tupleSum(element):
return sum(element)
alist.sort(key = tupleSum)
print("Ascending Order: " + str(alist))
alist.sort(key = tupleSum, reverse = True)
print("Descending Order: " + str(alist))
Original Order: [(12, 0, 9), (11, 1, 2), (12, 5, 3), (5, 3, 0), (3, 4, 8)]
Ascending Order: [(5, 3, 0), (11, 1, 2), (3, 4, 8), (12, 5, 3), (12, 0, 9)]
Descending Order: [(12, 0, 9), (12, 5, 3), (3, 4, 8), (11, 1, 2), (5, 3, 0)]
Note:
To use sort() function, compulsory list should contain only homogeneous elements, otherwise we
will get TypeError.
list=[20,10,"A","B"]
list.sort()
print(list)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-19-c63e865af43d> in <module>()
1 list=[20,10,"A","B"]
----> 2 list.sort()
3 print(list)

TypeError: '<' not supported between instances of 'str' and 'int'


Python List clear()
The method clear() is used to remove all the items from a given Python List. This method does not delete
the list but it makes the list empty.
Syntax
The following syntax empty the list.
list.clear()
#A list containing some items
items = ["Copy","Pen",10, 1.5, True, ('A','B')]

Department of Mechanical Engineering


19
RGM College of Engineering & Technology (Autonomous), Nandyal

print("Initial List:",items)
#Clearing all the list items
items.clear()
print("Empty List:",items)
Initial List: ['Copy', 'Pen', 10, 1.5, True, ('A', 'B')]
Empty List: []
Example. Deleting all list items using del keyword & Slicing Operator
* The code for the following example is exactly the same as above. The difference is just that we’ve used
the del keyword and the slicing operator to delete all the items from the list instead of the list.clear()
method.
#A list containing some items
items = ["Copy","Pen",10, 1.5, True, ('A','B')]
print("Initial List:",items)
#Clearing all the list items
#Using del keyword
del items[:]
print("Empty List:",items)
Initial List: ['Copy', 'Pen', 10, 1.5, True, ('A', 'B')]
Empty List: []
Built-in functions
print(all([' ', ',', '1', '2'])) # only 0 and false are treated as not true
True
print(all(['', 0, 1]))
False
print(any([' ', ',', '1', '2'])) # returns true if there is at least one True (anything other than 0 or False) in the
list
True
print(list(enumerate(['a','b','c','d','e']))) # if not work use del list
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]
print(max([1, 2, 3, 4, 5]))
5
print(min([1, 2, 3, 4, 5]))
1
origlist = [1, 5, 3, 4, 7, 9, 1, 27]
sortedlist = sorted(origlist)
print(sortedlist)

Department of Mechanical Engineering


20
RGM College of Engineering & Technology (Autonomous), Nandyal

[1, 1, 3, 4, 5, 7, 9, 27]
Sort() vs Sorted() :
The main difference between the sort() function and the sorted() function is that the sort function will
modify the list it is called on. The sorted() function will create a new sequence type containing a sorted
version of the sequence it is given. The sorted() function will not modify the sequence passed as a
parameter. If you want to sort a list but still have the original version, then you would use the sorted()
function. If maintaining the original order is unimportant, then you can call the sort() function on the
sequence.
print(sum([1, 5, 3, 4, 7, 9, 1, 27]))
print(sum([1, 3, 5, 'a', 'b', 4, 6, 7]))
57
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-74-cb4452331f6b> in <module>()
1 print(sum([1, 5, 3, 4, 7, 9, 1, 27]))
----> 2 print(sum([1, 3, 5, 'a', 'b', 4, 6, 7]))

TypeError: unsupported operand type(s) for +: 'int' and 'str'


Aliasing and Cloning of List objects:
* The process of giving another reference variable to the existing list is called aliasing.
Observe the following Python Code.
* list1 = [1,2,3,4,5]
* list2 = list1
In the above code, we have a list of 5 items. In the second line, we’ve used the = operator, thinking it will
create a copy of the list into the list2 variable. But is it like that?
list2 will not contain a copy of the list1, rather the list2 will only be a new reference variable for the list1.
It means the list of 5 items is now having two names, list1 and list2. In other words, it does not duplicate
the list. Any changes made to list1 will also be reflected in list2 because the list1 and list2 both point to
the same memory address.
To overcome this problem we should go for cloning.
* Cloning :The process of creating exactly duplicate independent object is called cloning.
We can implement cloning by using the following ways:
# 1. slice operator # 2. copy() function
#Python List copy()

Department of Mechanical Engineering


21
RGM College of Engineering & Technology (Autonomous), Nandyal

The list.copy() method is used to create a copy of the list into a new variable.
Now many of you might be questioning, why we need a method to copy a list into a new variable when
we can simply do it with the assignment operator = (equals to)?
Hence, we need the list.copy() method to actually create a new copy of a given list.
list_copy = list.copy()
#List1
list1 = ["Gurmeet","Jaskaran","Akshit","Sahil"]
#Copying list1 into list2
list2 = list1.copy()

#Making some changes in only list2


list2.append("Sheila")
print("Original List:",list1)
print("Copied List with Changes",list2)
Original List: ['Gurmeet', 'Jaskaran', 'Akshit', 'Sahil']
Copied List with Changes ['Gurmeet', 'Jaskaran', 'Akshit', 'Sahil', 'Sheila']
Example: Copying a Python List using Slicing Operator
The Slicing operator can also be used to create a fresh new copy of a Python List and this is illustrated in
the following example.
#List1
list1 = ["Gurmeet","Jaskaran","Akshit","Sahil"]
#Copying list1 into list2
#Using Slicing Operator
list2 = list1[:]
#Making some changes in only list2
list2.append("Sheila")
print("Original List:",list1)
print("Copied List with Changes",list2)
Original List: ['Gurmeet', 'Jaskaran', 'Akshit', 'Sahil']
Copied List with Changes ['Gurmeet', 'Jaskaran', 'Akshit', 'Sahil', 'Sheila']

Department of Mechanical Engineering


22
RGM College of Engineering & Technology (Autonomous), Nandyal

Q. What is the difference between = operator and copy() function?


= operator meant for aliasing copy() function meant for cloning
List comprehensions
* It is a great way of creating lists in Python without the need for individually specifying every element of
the list. This helps you to create logical and very large lists in just a single line of code, concisely.
* List Comprehension is basically a syntax in Python that lets you define the logic to create lists
dynamically. You basically define how each of the elements has to be created. So, when you define to the
computer how to generate the elements of the list, you eliminate the need of defining each and every
element of the list yourself. The computer will do the work for you.
* It is very easy and compact way of creating list objects from any iterable objects(like
list,tuple,dictionary,range etc) based on some condition.
* Syntax:
list=[expression for item in list if condition]
* A list comprehension generally consist of these parts :
Output expression
Input sequence
A variable representing a member of the input sequence and
An optional predicate part.
* Example: a = [x ** 2 for x in range (1, 11) if x % 2 == 1]
* Here:
x ** 2 is output expression,
range (1, 11) is input sequence,
x is variable and
if x % 2 == 1 is predicate part.
Output: [1, 9, 25, 49, 81]
* Consider an example, If you want to store squares of numbers form 1 to 10 in a list,

list_1=[]
for x in range(1,11):
list_1.append(x*x)
print(list_1)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Department of Mechanical Engineering


23
RGM College of Engineering & Technology (Autonomous), Nandyal

In the above case, the program consisting 4 lines of code. Now for the same purpose we will write the
following code in more concised way.
list_1 = [x*x for x in range(1,21)]
list_2 = [x for x in l1 if x % 2 == 0]
list_3 = [x for x in l1 if x % 2 == 1]
print(list_1)
print(list_2)
print(list_3)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
[4, 16, 36, 64, 100, 144, 196, 256, 324, 400]
[1, 9, 25, 49, 81, 121, 169, 225, 289, 361]

Syllabus
Tuples: Operations on tuples, important methods used on tuple.
Introduction to Tuples:
• Tuples are like lists, but their elements are fixed; that is, once a tuple is created, you cannot add new
elements, delete elements, replace elements, or reorder the elements in the tuple.
• The major differences between the two are: Lists are enclosed in square brackets [] and their
elements and size can be changed (mutable), while tuples are enclosed in parentheses () and their
elements cannot be changed (immutable).
• Tuples can be thought of as read-only lists.
• Note: Since a tuple is immutable, iterating through a tuple is faster than with a list. This gives a
slight performance improvement. Once a tuple is defined, we cannot add elements in it or remove
elements from it.
• A tuple can be converted into a list so that elements can be modified and converted back to a tuple.
• Tuple support both +ve and -ve index. +ve index means forward direction(from left to right) and -ve
index means backward direction(from right to left).
• A tuple is represented using parenthesis ( ). Sometimes parenthesis is optional.

Characteristics
• Maintains the order of the data insertion
• Tuples are immutable
• Tuples can contains the heterogeneous data
• Tuples allows duplicate data

Department of Mechanical Engineering


24
RGM College of Engineering & Technology (Autonomous), Nandyal

Applications:
• If the content is fixed, better to opt for tuple type.
• For example, In Banks, account type - Only 2 values are there, 1. Savings 2. Current At runtime
account types never going to change throughout Bank Project. So, to represent bank account types,
better to go for the tuple concept. Some other Examples, Where allowed inputs are fixed (Best
suitable type is tuple):
a. Vendor machines (Only accept 2/-,5/- coins only)
b. In the Metro stations also, If you want to get the tickets, you have to insert either 10/- note
or 20/- note only
Understanding basic tuple operations
• Creating a tuple
• indexing
• slicing
• Concatenation
• Repetition
• Membership
• Comparison
1. Creating a tuple
tuple_1 =5,6, 8, 9
tuple_2 =(5, 6, 8, 9)
print(tuple_1)
print(tuple_2)
print(type(tuple_1))
print(type(tuple_2))
(5, 6, 8, 9)
(5, 6, 8, 9)
<class 'tuple'>
<class 'tuple'>
# empty tuple
tuple =()
print(tuple)
print(type(tuple))
()
<class 'tuple'>

Department of Mechanical Engineering


25
RGM College of Engineering & Technology (Autonomous), Nandyal

Note:
We have to take special care about single valued tuple.compulsary the value should ends with
comma,otherwise it is not treated as tuple.
tuple = (10)
print(tuple)
print(type(tuple))
10
<class 'int'>
tuple = (10,)
print(tuple)
print(type(tuple))
(10,)
<class 'tuple'>
tuple = (10,20,30,)
print(tuple)
print(type(tuple))
(10, 20, 30)
<class 'tuple'>
By using tuple() function:
if you have any sequence (i.e., string, list, range etc.,) which can be easily converted into a tuple by using
tuple() function.
list=[10,20,30]
t=tuple(list)
print(t)
print(type(t))
(10, 20, 30)
<class 'tuple'>
t=tuple(range(10,20,2))
print(t)
print(type(t))
(10, 12, 14, 16, 18)
<class 'tuple'>
t = tuple('engineering')
print(t)
print(type(t))
('e', 'n', 'g', 'i', 'n', 'e', 'e', 'r', 'i', 'n', 'g')
<class 'tuple'>

Department of Mechanical Engineering


26
RGM College of Engineering & Technology (Autonomous), Nandyal

Accessing elements of tuple:


We can access elements of a tuple either by using index or by using slice operator.
#1. By using index:
t=(10,20,30,40,50,60)
print(t[0]) #10
print(t[-1]) #60
print(t[100]) #IndexError: tuple index out of range
10
60
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-13-ba1aec3992ff> in <module>()
3 print(t[0]) #10
4 print(t[-1]) #60
----> 5 print(t[100]) #IndexError: tuple index out of range

IndexError: tuple index out of range


#2. By using slice operator:
t=(10,20,30,40,50,60)
print(t[2:5]) #30,40,50
print(t[2:100]) # 30,40,50,60
print(t[::2]) #10,30,50
(30, 40, 50)
(30, 40, 50, 60)
(10, 30, 50)
t= tuple('engineering')
print(t[0])
print(t[1:5:1])
print(t[-2:-5:-1])
e
('n', 'g', 'i', 'n')
('n', 'i', 'r')
Tuple vs immutability:
Once we creates tuple,we cannot change its content. Hence tuple objects are immutable.
t=(10,20,30,40)
t[1]=70
print(t)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)

Department of Mechanical Engineering


27
RGM College of Engineering & Technology (Autonomous), Nandyal

<ipython-input-16-e0f1d773bd10> in <module>()
1 t=(10,20,30,40)
----> 2 t[1]=70
3 print(t)

TypeError: 'tuple' object does not support item assignment


# Modifying Tuple Items
aTuple = ("Tutorial","Lesson","Teaching", 21)
#Converting Tuple To List
aList = list(aTuple)
#Modify Items
aList[1] = "Hello"
aList[2] = "Good"
#Converting List Back to Tuple
aTuple = tuple(aList)
#Modified tuple
print(aTuple)
('Tutorial', 'Hello', 'Good', 21)
Mathematical operators for tuple:
We can apply + and * operators for tuple
#1. Concatenation Operator(+):
t1=(10,'mech',30, 'engineering')
t2=(40,'how',60, 'well')
t3=t1+t2
print(t3)
(10, 'mech', 30, 'engineering', 40, 'how', 60, 'well')
t1 = 10,20,30,40
t2 = 10,20,30,40
t3 = t1 + t2 # because list and tuple allow duplicates, so you will get all the elements
print(t3)
(10, 20, 30, 40, 10, 20, 30, 40)
#2. Multiplication operator (or) repetition operator(*):
t1=(10,20,30)
t2=t1*3
print(t2) #(10,20,30,10,20,30,10,20,30)
(10, 20, 30, 10, 20, 30, 10, 20, 30)
#Iterating a Tuple
aTuple = ("Tutorial","Lesson","Teaching", 21)

Department of Mechanical Engineering


28
RGM College of Engineering & Technology (Autonomous), Nandyal

for item in aTuple:


print(item)
Tutorial
Lesson
Teaching
21
Checking If Items Exists in the Tuple
Membership operators
• in and not in can be used to check if a particular item exists in the tuple or not.
a = (2, 3, 4, 5, 6, 7, 8, 9, 10)
print(5 in a)
print(100 in a)
print(2 not in a)
True
False
False
Comparison operators
Returns True if all elements in both tuples are same otherwise returns false.
a = (2, 3, 4, 5, 6, 7, 8, 9, 10)
b = (2, 3, 4)
print(a == b)
print(a != b)
print(a < b)
print(a > b)
print(a <= b)
print(a >= b)
False
True
False
True
False
True
Understanding the Built-in Tuple Functions
List of functions that can be applied on tuple are given below:
#all(): Returns True if all the items in the tuple has a True value
print(all((' ', ',', '1', '2')))
True

Department of Mechanical Engineering


29
RGM College of Engineering & Technology (Autonomous), Nandyal

#any(): Returns True if even one item in the tuple has a True value
print(any((' ', ',', '1', '2')))
True
# enumerate(): Returns an enumerate object consisting of the index and value of all items of a tuple as
pairs
x = (1, 2, 3, 4, 5, 6)
print(tuple(enumerate(x)))
((0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6))
# len(): This function calculates the length i.e., the number elements in the tuple
x = (1, 2, 3, 4, 5, 6)
print(len(x))
6
# max(): This function returns the item with the highest value in the tuple
print(max((1, 2, 3, 4, 5, 6)))
t = ('engineering') # based on unicode values these functions will work.
print(max(t))
6
r
# min(): This function returns the item with the lowest value in the tuple
print(min((1, 2, 3, 4, 5, 6)))
t = ('engineering') # based on unicode values these functions will work.
print(min(t))
1
e
# sorted(): This function returns a sorted result of the tuple which is a list, with the original tuple
unchanged.
origtup = (1, 5, 3, 4, 7, 9, 1, 27)
sorttup = sorted(origtup)
print(sorttup)
print(origtup)
[1, 1, 3, 4, 5, 7, 9, 27]
(1, 5, 3, 4, 7, 9, 1, 27)
# sum(): This function returns the sum of all elements in the tuple.
# This function works only on numeric values in the tuple and will error out if the tuple contains a mix of
string and numeric values.
print(sum((1, 5, 3, 4, 7, 9, 1, 27)))
print(sum((1, 'hi', 3, 4, 7, 'how', 1, 27)))
57

Department of Mechanical Engineering


30
RGM College of Engineering & Technology (Autonomous), Nandyal

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-34-b7b5c79dffbd> in <module>()
2 # This function works only on numeric values in the tuple and will error out if the tuple contains a
mix of string and numeric values.
3 print(sum((1, 5, 3, 4, 7, 9, 1, 27)))
----> 4 print(sum((1, 'hi', 3, 4, 7, 'how', 1, 27)))

TypeError: unsupported operand type(s) for +: 'int' and 'str'


# tuple(): This function converts an iterable (list, string, set, dictionary) to a tuple
x = list("abcdef")
print(x)
print(tuple(x))
['a', 'b', 'c', 'd', 'e', 'f']
('a', 'b', 'c', 'd', 'e', 'f')
Important functions of Tuple
# 1. len():It is used to return number of elements present in the tuple.
t=(10,20,30,40)
print(len(t))
4
# 2. count(): To return number of occurrences of given element in the tuple
t=(10,20,10,10,20)
print(t.count(10))
3
# 3. index(): It returns index of first occurrence of the given element. If the specified element is not
available then we will get ValueError.
t=(10,20,10,10,20)
print(t.index(10)) # 0
print(t.index(30))
0
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-38-23421a9fb8f3> in <module>()
2 t=(10,20,10,10,20)
3 print(t.index(10)) # 0
----> 4 print(t.index(30))

ValueError: tuple.index(x): x not in tuple

Department of Mechanical Engineering


31
RGM College of Engineering & Technology (Autonomous), Nandyal

# 4. sorted(): It is used to sort elements based on default natural sorting order (Ascending order).
t =(10,30,40,20)
print(sorted(t))
[10, 20, 30, 40]
# We can sort according to reverse of default natural sorting order is as follows:
t =(10,30,40,20)
t1=sorted(t,reverse=True)
print(t1)
[40, 30, 20, 10]
Tuple Packing and Unpacking:
Tuple packing : We can create a tuple by packing a group of variables.
a=10
b=20
c=30
d=40
t=a,b,c,d
print(t) #(10, 20, 30, 40)
(10, 20, 30, 40)
Here a,b,c,d are packed into a tuple t. This is nothing but tuple packing.
a = 10
b = 20
c = 30
d = 40
t =[a,b,c,d]
print(type(t))
print(t)
<class 'list'>
[10, 20, 30, 40]
a = 10
b = 20
c = 30
d = 40
t ={a,b,c,d} # for 'set' order is not important
print(type(t))
print(t)
<class 'set'>
{40, 10, 20, 30}
a = 10
b = 20

Department of Mechanical Engineering


32
RGM College of Engineering & Technology (Autonomous), Nandyal

c = 30
d = 40
t ='a,b,c,d'
print(type(t))
print(t)
<class 'str'>
a,b,c,d
Tuple unpacking :
• Tuple unpacking is the reverse process of tuple packing.
• We can unpack a tuple and assign its values to different variables.
t=(10,20,30,40)
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d)
a= 10 b= 20 c= 30 d= 40
Note : This concept is also applicable for any sequence (i.e., string,list,set etc.,) concept also.
t=[10,20,30,40]
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d)
a= 10 b= 20 c= 30 d= 40
t={10,20,30,40}
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d)
a= 40 b= 10 c= 20 d= 30
t='abcd'
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d)
a= a b= b c= c d= d
Note:
At the time of tuple unpacking the number of variables and number of values should be same. ,otherwise
we will get ValueError
t=(10,20,30,40)
a,b,c=t
print("a=",a,"b=",b,"c=",c)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-52-42c848936d4d> in <module>()
1 t=(10,20,30,40)

Department of Mechanical Engineering


33
RGM College of Engineering & Technology (Autonomous), Nandyal

----> 2 a,b,c=t
3 print("a=",a,"b=",b,"c=",c)

ValueError: too many values to unpack (expected 3)


Tuple Comprehension
• Tuple Comprehension is not supported by Python.
• t= ( x**2 for x in range(1,6))
• Here we are not getting tuple object and we are getting generator object.
t= ( x**2 for x in range(1,6))
print(type(t))
for x in t:
print(x)
<class 'generator'>
1
4
9
16
25

Syllabus
Sets: Operations on sets, important methods used on set.
Introduction to Set
* A set is a mutable data type and We can add or remove items / elements from it.
* The elements in a Set cannot be changed (immutable).
* The set data type is, as the name implies, a mathematical set. we can perform operations like
union, intersection, difference and symmetric difference.
* Set does not allow duplicates. Set does not maintain order. This is because the placement of each
value in the set is decided by an arbitrary index produced by the hash() function.
As the implementation of the built-in hash() function is complex to understand now. To make it simple,
assume that, when we pass 'n' to hash() function,i.e, calling hash(n), returns n%10.
For example, calling hash(35) results 35 % 10, which is 5.

Hashing is the process of translating values to unique numbers, generally called a hash code. These
numbers are utilised by other data structures like sets and dictionaries to allocate a slot(bucket) in an
array.

Department of Mechanical Engineering


34
RGM College of Engineering & Technology (Autonomous), Nandyal

Department of Mechanical Engineering


35
RGM College of Engineering & Technology (Autonomous), Nandyal

* Internally uses a hash table. Values are translated to indices of the hash table using the hash() function.
When a collision occurs in the hash table, it ignores the element.
This explains, why sets unlike lists and tuples can't have multiple occurrences of the same element. type()
of set is 'set'.
* index and slicing concept is not applicable
* A set is represented with { }.
The main operations that can be performed on a set are:
* Membership test
* Eliminating duplicate entries.
* Mathematical set operations like union, intersection, difference and symmetric difference.
Characteristics:
* A set is a mutable data type and We can add or remove items / elements from it.
* The elements in a Set cannot be changed (immutable). Insertion order is not preserved.
* Duplicates are not allowed.
* Indexing and slicing not allowed for the set.
* Heterogeneous elements are allowed.
Creation of Set Objects
i) Creation of set object with single value
s = {10}
print(type(s))
print(s)
<class 'set'>
{10}
ii) Creation of set object with multiple values
numset = {1, 2, 3, 4, 5, 3, 2}
print(numset)
{1, 2, 3, 4, 5}
s = {30,40,10,5,20} # in the output order not preserved
print(type(s))
print(s[0])
<class 'set'>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-72e199601121> in <module>()

Department of Mechanical Engineering


36
RGM College of Engineering & Technology (Autonomous), Nandyal

1 s = {30,40,10,5,20} # in the output order not preserved


2 print(type(s))
----> 3 print(s[0])

TypeError: 'set' object is not subscriptable


s = {30,40,10,5,20} # in the output order not preserved
print(type(s))
print(s[0:6])
<class 'set'>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-3077da98f87a> in <module>()
1 s = {30,40,10,5,20} # in the output order not preserved
2 print(type(s))
----> 3 print(s[0:6])

TypeError: 'set' object is not subscriptable


iii) Creation of set objects using set() function
Syntax: s=set(any sequence)
list = [10,20,30,40,10,20,10]
s=set(list)
print(s)
{40, 10, 20, 30}
s=set(range(10))
print(s)
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
s = set('mechanical')
print(s)
{'n', 'h', 'c', 'a', 'm', 'e', 'l', 'i'}
Note:
* While creating empty set we have to take special care. Compulsory we should use set() function.
* s={} ==>It is treated as dictionary but not empty set.
s = {}
print(type(s))
<class 'dict'>

Department of Mechanical Engineering


37
RGM College of Engineering & Technology (Autonomous), Nandyal

s = set() # set function without any arguments


print(s)
print(type(s))
set()
<class 'set'>
Accessing or Changing Set Items
You can not either access or change a particular set element. The reason being sets are unindexed.
Loop Through Set Elements
Although you can not access individual set items yet you can always use the Python For Loop to
access one item at a time.
#set of fruits
fruits = {'Apple', 'Banana', 'Cherry', 'Dates'}

#loop through fruits


for fruit in fruits:
print(fruit)
Apple
Cherry
Dates
Banana
Note. You can observe in the output that the items are looped through in a different order than they
actually defined set order. This again shows the unindexed and unordered property of the set.
Check If An item Exists in a Set (Membership Test)
As a set is a collection object, so we can apply the membership operators i.e. in and not in to find out if a
particular item is present in a given set or not. These operators return a boolean value i.e. True if a given
item founds in a given set and False a given item does not found in a given set.
countries = {"India", "USA", "UK", "Canada", "Japan"}

#Checking if Japan present in countries


#returns True
print("Japan" in countries)

#Checking if Italy present in countries


#returns False
print("Italy" in countries)

#Checking if the UK not present in countries


#returns False
print("UK" not in countries)

Department of Mechanical Engineering


38
RGM College of Engineering & Technology (Autonomous), Nandyal

#Checking if Brazil not present in countries


#returns True
print("Brazil" not in countries)
True
False
False
True
Python set() Operations
1. Set Union
The union of two sets is the set of all the elements of both the sets without duplicates. You can use the
union() method or the | syntax to find the union of a Python set.

A = {1, 2, 3, 4, 5, 6}
B = {4, 5, 6, 7, 8, 9}

#Union of A & B using | Operator


A_UNION_B = A | B

print("A ⋃ B:", A_UNION_B)

#Union of A & B using the union() method


A_UNION_B = A.union(B)
B_UNION_A = B.union(A)

print("A ⋃ B:", A_UNION_B)


print("B ⋃ A:", B_UNION_A)
A ⋃ B: {1, 2, 3, 4, 5, 6, 7, 8, 9}
A ⋃ B: {1, 2, 3, 4, 5, 6, 7, 8, 9}
B ⋃ A: {1, 2, 3, 4, 5, 6, 7, 8, 9}

Department of Mechanical Engineering


39
RGM College of Engineering & Technology (Autonomous), Nandyal

2. Set Intersection
The intersection of two sets is the set of all the common elements of both the sets. You can use the
intersection() method of the & operator to find the intersection of a Python set.

A = {1, 2, 3, 4, 5, 6}
B = {4, 5, 6, 7, 8, 9}

#Intersection of A and B using & Operator


A_INTERSECT_B = A & B

print("A ⋂ B:", A_INTERSECT_B)

#Intersection of A and B using the intersection() method


A_INTERSECT_B = A.intersection(B)
B_INTERSECT_A = B.intersection(A)

print("A ⋂ B:", A_INTERSECT_B)


print("B ⋂ A:", B_INTERSECT_A)
3. Set Difference
If there are two sets, A and B, then the difference of the set B from set A i.e. A - B will be a set
containing all the items that are only present in set A and not in set B. Similarly, the difference of the set
A from set B i.e. B - A will be a set containing all the items that are only present in set B and not in set A.

Department of Mechanical Engineering


40
RGM College of Engineering & Technology (Autonomous), Nandyal

A = {1, 2, 3, 4, 5, 6}
B = {4, 5, 6, 7, 8, 9}

#Differnce of Set B from Set A


#Using – operator
print(A - B)

#Differnce of the Set A from Set B


#Using – operator
print(B - A)

#Differnce of Set B from Set A


#Using the method difference()
print(A.difference(B))

#Differnce of the Set A from Set B


#Using the method difference()
print(B.difference(A))
{1, 2, 3}
{8, 9, 7}
{1, 2, 3}
{8, 9, 7}
4. Set Symmetric Difference
The symmetric difference of the Set A and B is the set of all the elements that are not common between
the two sets. In other words, it is the set of all the elements of union excluding the intersection elements.

To find out the set difference, you can either use the ^ operator or the symmetric_difference() method on
a given set. The code given below illustrates the usage of this operator and method.
A = {1, 2, 3, 4, 5, 6}
B = {4, 5, 6, 7, 8, 9}

Department of Mechanical Engineering


41
RGM College of Engineering & Technology (Autonomous), Nandyal

#Symmetric Difference of Set A and Set B


#Using ^ Operator
symm_diff = A ^ B

print(symm_diff)

#Symmetric Difference of Set A and Set B


#Using symmetric_difference() method
symm_diff = A.symmetric_difference(B)

print(symm_diff)
{1, 2, 3, 7, 8, 9}
{1, 2, 3, 7, 8, 9}
Other Set Operations in Python
These are not so common, but they're useful in seeing how sets relate to others.
the a.issubset(b) method or <= operator returns true if the a is a subset of b
the a.issuperset(b) method or >= operator returns true if the a is a superset of b
the a.isdisjoint(b) method return true if there are no common elements between sets a and b
Built-in Functions that work with Python Sets
1. all() Function: This method returns a boolean value i.e. either True or False.
* If all the elements of the iterable object will be True or representing True, it will return True.
* If at least one of the elements of the iterable object will be False or will indicate a False value, it will
return False.
* If the iterable object is empty, it also returns True.
#Example 1. Checking all() Method For Different Iterables
#Boolean List with all items as True
list1 = [True, True, True]
#Numerical Elements
#0 Represents False and all other integers represents True
list2 = [1, 2, 3, 5]

#Boolean List with all items as False


list3 = [False, False, False]
#Numerical Elements
list4 = [0, 0, 0, 0]
#Atleast One-Element is False in the List
list5 = [True, False, True]
list6 = [1, 2, 0, 5]

Department of Mechanical Engineering


42
RGM College of Engineering & Technology (Autonomous), Nandyal

#Some other Random cases


list7 = [1, 1, True, False, 1]
list8 = [9, False, 5, False]
list9 = [10, 20, 30, True]
list10 = [True, True, 100, 80, 0]

#all() Method Outputs


print(all(list1))
print(all(list2))
print(all(list3))
print(all(list4))
print(all(list5))
print(all(list6))
print(all(list7))
print(all(list8))
print(all(list9))
print(all(list10))

#All String Characters represents True


#Although 0 as an integer represents False
#But '0' as a String is True
string1 = "Hello, this is a Python Tutorial!"
string2 = "00000"
string3 = "The number starts with 0 and ends with 1."
string4 = "Why the number starts with 0?"

#Checking all() Method's Return Values


#All True
print(all(string1))
print(all(string2))
print(all(string3))
print(all(string4))

#Integer Keys and only the First Key is False


check1 = {0 : "True", 1 : False}

#String Keys, all True


check2 = {"0" : "False", "1": False}
check3 = {"a" : False, "b": True}

#Boolean Keys, second False


check4 = {True: "ok", False: "Not ok"}

Department of Mechanical Engineering


43
RGM College of Engineering & Technology (Autonomous), Nandyal

print(all(check1))
print(all(check2))
print(all(check3))
print(all(check4))
True
True
False
False
False
False
False
False
True
False
True
True
True
True
False
True
True
False
all() Returns True for all empty Iterables
As mentioned earlier as well, for any iterable containing no elements, this method all() will always
return True.
#Empty Dictionary
print(all({}))

#Empty list
print(all([]))

#Empty tuple
print(all(()))

#Empty String
print(all(""))
True
True
True
True

Department of Mechanical Engineering


44
RGM College of Engineering & Technology (Autonomous), Nandyal

2. Python any() Function


The Python’s built-in function any() is used to check if an iterable python object contains at least
one item that is True. It returns True if the iterable to check contains any True element and if it
does not contain any of the element that is True, it returns False.
#Boolean List with all items as True
list1 = [True, True, True]
#Numerical Elements
#0 Represents False and all other integers represents True
list2 = [1, 2, 3, 5]

#Boolean List with all items as False


list3 = [False, False, False]
#Numerical Elements
list4 = [0, 0, 0, 0]

#Atleast One-Element is False in the List


list5 = [True, False, True]
list6 = [1, 2, 0, 5]

#Some other Random cases


list7 = [1, 1, True, False, 1]
list8 = [9, False, 5, False]
list9 = [10, 20, 30, True]
list10 = [True, True, 100, 80, 0]

#any() Method Outputs


print(any(list1))
print(any(list2))
print(any(list3))
print(any(list4))
print(any(list5))
print(any(list6))
print(any(list7))
print(any(list8))
print(any(list9))
print(any(list10))

#All String Characters represents True


#Although 0 as an integer represents False
#But '0' as a String is True
string1 = "Hello, this is a Python Tutorial!"
string2 = "00000"
string3 = "The number starts with 0 and ends with 1."

Department of Mechanical Engineering


45
RGM College of Engineering & Technology (Autonomous), Nandyal

string4 = "Why the number starts with 0?"

#Checking any() Method's Return Values


#All True
print(any(string1))
print(any(string2))
print(any(string3))
print(any(string4))

#Integer Keys and only the First Key is False


check1 = {0 : "True", 1 : False}

#String Keys, all True


check2 = {"0" : "False", "1": False}
check3 = {"a" : False, "b": True}

#Boolean Keys, second False


check4 = {True: "ok", False: "Not ok"}

#Single Key False

check5 = {False: "Not ok!"}


True
True
False
False
True
True
True
True
True
True
True
True
True
True
Applying any() on Empty Iterables
For any of the empty iterables whether it’s a Python List, Dictionary, Tuple or a String, this
method is going to return False always.
#Empty Dictionary
print(any({}))

Department of Mechanical Engineering


46
RGM College of Engineering & Technology (Autonomous), Nandyal

#Empty list
print(any([]))

#Empty tuple
print(any(()))

#Empty String
print(any(""))
False
False
False
False
Python enumerate() Function
In python, enumerate() is a very useful function that can automatically assign sequenced numbering to
different iterable objects. This function will return an Enumerate Type object, which can be easily iterated
using Python For Loop or While Loop. You can also directly convert this enumerate type object into a
more readable iterable like Python List.
Syntax
The syntax of the enumerate() function is given below.
enumerateObject = enumerate(iterable, start = 0)
vegetables = ["Potato","Tomato","Peas","Cauliflower"]
fruits = ("Mango","Apple","Papaya")
#Non-Numbered List
print(vegetables)
#Non-Numbered tuple
print(fruits)
#Enumerating List
vegetables = enumerate(vegetables)
#Enumerating Tuple, setting starting index as 5
fruits = enumerate(fruits,5)
#Converting Enumerable Object To Tuple
vegetables = tuple(vegetables)
#Converting Enumerable Object To List
fruits = list(fruits)
#Numbered vegetables Tuple
print(vegetables)
#Numbered fruits List
print(fruits)
['Potato', 'Tomato', 'Peas', 'Cauliflower']
('Mango', 'Apple', 'Papaya')

Department of Mechanical Engineering


47
RGM College of Engineering & Technology (Autonomous), Nandyal

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-26-0b17de878f2a> in <module>()
12 vegetables = tuple(vegetables)
13 #Converting Enumerable Object To List
---> 14 fruits = list(fruits)
15 #Numbered vegetables Tuple
16 print(vegetables)

TypeError: 'list' object is not callable


Doing iteration using enumerate()
You can also do numbered iteration using the enumerate() function easily. The following example
illustrates the same.
cities = ["Ludhiana","Chandigarh","Amritsar","Jalandhar"]
print("List of Cities")
for city in cities:
print(city)

print("\nList of Cities with Numbering")


for city in enumerate(cities):
print(city)

print("\nList of Cities with Ranks")


for rank, city in enumerate(cities):
print(rank, city)

print("\nList of Cities With Rank Starting From 3")


for rank, city in enumerate(cities, 3):
print(rank, city)
List of Cities
Ludhiana
Chandigarh
Amritsar
Jalandhar

List of Cities with Numbering


(0, 'Ludhiana')
(1, 'Chandigarh')
(2, 'Amritsar')
(3, 'Jalandhar')

List of Cities with Ranks

Department of Mechanical Engineering


48
RGM College of Engineering & Technology (Autonomous), Nandyal

0 Ludhiana
1 Chandigarh
2 Amritsar
3 Jalandhar

List of Cities With Rank Starting From 3


3 Ludhiana
4 Chandigarh
5 Amritsar
6 Jalandhar
Python len() Function
The built-in function len() is used to find out the number of items or elements contained in a Python
Object. For some Pythons, rather than saying finding the number of items, you can use this function
actually to calculate the length of the object.
count = len(sequenceObject)
#An Empty List
aEmptyList = []

#A List with 5 elements


aList = ['A','B','C','D','E']

#A Tuple with 3 elements


aTuple = (1,2,3)

#Range object from 1 To 94


aRange = range(1,95)

#Finding items count using the len() Function


#For each of these collection objects

print(len(aEmptyList))
print(len(aList))
print(len(aTuple))
print(len(aRange))

0
5
3
94

Department of Mechanical Engineering


49
RGM College of Engineering & Technology (Autonomous), Nandyal

Calculating Length of String and Bytes Objects using len() Method


#An Empty String
anEmptyString = ""

#An Empty Byte object


anEmptyBytesObject = b''

#String with some chracters


aString = "Python @ WTMatter.com"

#Byte Oject with some chracters


aByteObject = b'Enjoy Python Programming!'

#Byte Object
unicodeByte = b'\xe0\xa4\xa8\xe0\xa4\xae\xe0\xa4\xb8\xe0\xa5\x8d\xe0\xa4\x95\xe0\xa4\xbe\xe0\xa4\
xb0'

#Finding Length of each of these objects


print(len(anEmptyString))
print(len(anEmptyBytesObject))
print(len(aString))
print(len(aByteObject))
print(len(unicodeByte))
0
0
21
25
21
Finding Length of Dictionary and Set Objects using len() Function
#An Empty Dictionary
emptyDictionary = {}

#An Empty Set


emptySet = set()

#An Empty Frozenset


emptyFrozenSet = frozenset(emptySet)

#A Dictionary with some elements


aDictionary = {"Name": "Gurmeet Singh", "Score": 100}

#A Set with some elements

Department of Mechanical Engineering


50
RGM College of Engineering & Technology (Autonomous), Nandyal

aSet = set(aDictionary)

#A Frozen set with some elements


aFrozenSet = frozenset(aSet)

#Finding elements count for each using len()


print(len(emptyDictionary))
print(len(emptySet))
print(len(emptyFrozenSet))
print(len(aDictionary))
print(len(aSet))
print(len(aFrozenSet))
0
0
0
2
2
2
max()
It returns the largest item present in a given set.
min()
It returns the smallest item present in a given set.
sorted()
It returns a new list that contains the set elements in sorted order.
sum()
It returns the sum of all of the set items.

Python Set Methods


1. add(x):
Adds item x to the set
s={10,20,30}
s.add(40); # ';' is optional for python statements
print(s)
{40, 10, 20, 30}
s={10,20,30}
s.add('mechanical'); # ';' is optional for python statements
print(s)
{'mechanical', 10, 20, 30}

Department of Mechanical Engineering


51
RGM College of Engineering & Technology (Autonomous), Nandyal

2. update(x, y, z)
It updates the set after doing union of itself with another set.
* This method is used to add multiple items to the set.
* Arguments are not individual elements and these are Iterable objects like List,range etc.
* All elements present in the given Iterable objects will be added to the set
s={10,20,30}
s.update('mechanical'); # ';' is optional for python statements
print(s)
{'n', 10, 'h', 'i', 'c', 'a', 'm', 20, 'e', 'l', 30}
s={10,20,30}
l=[40,50,60,10]
s.update(l,range(5))
print(s)
{0, 1, 2, 3, 4, 40, 10, 50, 20, 60, 30}
s={10,20,30}
l=[40,50,60,10]
s.update(l,range(5),100)
print(s)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-36-96e519440e16> in <module>()
1 s={10,20,30}
2 l=[40,50,60,10]
----> 3 s.update(l,range(5),100)
4 print(s)

TypeError: 'int' object is not iterable


s={10,20,30}
l=[40,50,60,10]
s.update(l,range(5),'100')
print(s)
{0, 1, 2, 3, 4, '0', 40, 10, '1', 50, 20, 60, 30}
s={10,20,30}
l=[40,50,60,10]
s.update(l,range(5),'mechanical')
print(s)
{0, 1, 2, 3, 4, 10, 'c', 20, 30, 40, 50, 'm', 60, 'h', 'a', 'i', 'n', 'e', 'l'}

Department of Mechanical Engineering


52
RGM College of Engineering & Technology (Autonomous), Nandyal

s =set()
s.update(range(1,10,2),range(0,10,2))
print(s)
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
Q. What is the difference between add() and update() functions in set?
We can use add() to add individual item to the Set,whereas we can use update() function to add multiple
items to Set.
add() function can take only one argument where as update() function can take any number of arguments
but all arguments should be iterable objects like strings, lists, tuple, dictionary, set etc.
3. copy():
Returns copy of the set. It is cloned object (Backup copy)
s={10,20,30}
s1=s.copy()
print(s1)
print(s)
{10, 20, 30}
{10, 20, 30}
4. pop():
It removes and returns some random element from the set.
s={40,10,30,20}
print(s)
print(s.pop())
print(s.pop())
print(s.pop())
print(s)
print(s.pop())
print(s) # empty set
print(s.pop())
{40, 10, 20, 30}
40
10
20
{30}
30
set()
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-41-e74fb62025b2> in <module>()
7 print(s.pop())

Department of Mechanical Engineering


53
RGM College of Engineering & Technology (Autonomous), Nandyal

8 print(s) # empty set


----> 9 print(s.pop())

KeyError: 'pop from an empty set'


5. remove(x):
It removes specified element from the set.
If the specified element not present in the Set then we will get KeyError.
s={40,10,30,20}
s.remove(30)
print(s) # {40, 10, 20}
s.remove(50) # KeyError: 50
{40, 10, 20}
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-42-77437864d839> in <module>()
2 s.remove(30)
3 print(s) # {40, 10, 20}
----> 4 s.remove(50) # KeyError: 50

KeyError: 50
6. discard(x):
It removes the specified element from the set. If the specified element not present in the set then we won't
get any error.
s={10,20,30}
s.discard(10)
print(s) #{20, 30}
s.discard(50)
print(s) #{20, 30}
{20, 30}
{20, 30}
7.clear():
To remove all elements from the Set.
s={10,20,30}
print(s)
s.clear()
print(s)
{10, 20, 30}
set()

Department of Mechanical Engineering


54
RGM College of Engineering & Technology (Autonomous), Nandyal

Set Comprehension
Set comprehension is possible.
Syntax: # s = {expression for x in sequence condition}
s = {x*x for x in range(6)}
print(s)
{0, 1, 4, 9, 16, 25}
s={2**x for x in range(2,10,2)}
print(s)
{16, 256, 64, 4}
Syllabus
Dictionaries: Operations on Dictionaries, important methods used on dictionaries.
Introduction to dictionary
• We can use List,Tuple and Set to represent a group of individual objects as a single entity.
• If we want to represent a group of objects as key-value pairs then we should go for Dictionary.
• Dictionary is an unordered collections of unique values stored in key and value pairs.
• General usage of dictionaries is to store key-value pairs like :
– Employees and their wages
– Countries and their capitals
– Commodities and their prices
– Students roll numbers and their names
– Mobile numbers and their address
– ipaddress and its domain name
• In a dictionary, the keys should be unique, but the values can change. For example, the price of a
commodity may change over time, but its name will not change.
• Immutable data types like number, string, tuple etc. are used for the key and any data type is used
for the value.
• Dictionaries are represented by curly braces {}.
• The key-value pairs are represented as key : value.
• For example, daily temperatures in major cities are mapped into a dictionary as { "Hyderabad" : 27 ,
"Chennai" : 32 , "Mumbai" : 40 }.
Key features of Dictionary Data type :
2. Duplicate keys are not allowed but values can be duplicated.
3. Hetrogeneous objects are allowed for both key and values.

Department of Mechanical Engineering


55
RGM College of Engineering & Technology (Autonomous), Nandyal

4. insertion order is not preserved.


5. Dictionaries are mutable.
6. Dictionaries are dynamic.
7. indexing and slicing concepts are not applicable.
Overview of Operations
• The typical operations that can be performed on a dictionary are:
– Adding elements i.e., Key:Value pairs.
– Accessing elements using the Key with the Index operator [] or using get() method.
– Updating the value of a particular element given in the Key.
– The elements can also be deleted which results in a deletion of both the key:value pair or
deleting the entire dictionary using del() method.
– Iterating through a dictionary for processing the elements in it.
Creation of Dictionary objects
1. If you want to create an empty dictionary, we use the following approaches:
* {}
* dict()
d = {}
print(type(d))
print(d)
# using dict()
dictionary = dict()
print(type(d))
print(dictionary)
<class 'dict'>
{}
<class 'dict'>
{}
2. dictionary with some initial values.
details = {
"Department" : "Mechanical Engineering",
"Established" : 1995,
"College" : "RGMCET",
"Located at": "Nandyal"
}
print(details)

Department of Mechanical Engineering


56
RGM College of Engineering & Technology (Autonomous), Nandyal

{'Department': 'Mechanical Engineering', 'Established': 1995, 'College': 'RGMCET', 'Located at':


'Nandyal'}
Adding & Changing Values
details = {}
#adding new items
details['department'] = 'mechanical'
details['college'] = 'rgmcet'
details['established'] = 1995
print(details)
{'department': 'mechanical', 'college': 'rgmcet', 'established': 1995}
details = {}
#adding new items
details['department'] = 'mechanical'
details['college'] = 'rgmcet'
details['established'] = 1995
print(details)
#changing values
details['department'] = 'computer science'
print(details)
{'department': 'mechanical', 'college': 'rgmcet', 'established': 1995}
{'department': 'computer science', 'college': 'rgmcet', 'established': 1995}
Accessing data from the dictionary
• We can access data by using keys.
• If the specified key is not available then we will get KeyError.
• We can prevent this by checking whether key is already available or not by using in operator.
details = {
"Department" : "Mechanical Engineering",
"Established" : 1995,
"College" : "RGMCET",
"Located at": "Nandyal"
}
print(details['College'])
print(details['State'])
if 'State' in details:
print(details['State'])
RGMCET
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-20-80c7d8fdf571> in <module>()

Department of Mechanical Engineering


57
RGM College of Engineering & Technology (Autonomous), Nandyal

6}
7 print(details['College'])
----> 8 print(details['State'])
9 if 'State' in details:
10 print(details['State'])

KeyError: 'State'
Example Program Q. Write a program to enter name and percentage marks in a dictionary and
display information on the screen.
rec={}
n=int(input("Enter number of students: "))
i=1
while i <= n:
name=input("Enter Student Name: ")
marks=input("Enter % of Marks of Student: ")
rec[name]=marks
i=i+1
print("Name of Student","\t","% of Marks")
for x in rec:
print("\t",x,"\t",rec[x])
Enter number of students: 2
Enter Student Name: rai
Enter % of Marks of Student: 67
Enter Student Name: giri
Enter % of Marks of Student: 69
Name of Student % of Marks
rai 67
giri 69
Deleting the elements from Dictionary
Syntax : del d[key]
• It deletes entry associated with the specified key.
• If the key is not available then we will get KeyError.
details = {
"Department" : "Mechanical Engineering",
"Established" : 1995,
"College" : "RGMCET",
"Located at": "Nandyal"
}
print(details)

Department of Mechanical Engineering


58
RGM College of Engineering & Technology (Autonomous), Nandyal

del details['College']
print(details)
{'Department': 'Mechanical Engineering', 'Established': 1995, 'College': 'RGMCET', 'Located at':
'Nandyal'}
{'Department': 'Mechanical Engineering', 'Established': 1995, 'Located at': 'Nandyal'}
Printing Dictionary Values using key
details = {
"Department" : "Mechanical Engineering",
"Established" : 1995,
"College" : "RGMCET",
"Located at": "Nandyal"
}
for key in details:
print(details[key])
Mechanical Engineering
1995
RGMCET
Nandyal
Printing Dictionary Values using value()
details = {
"Department" : "Mechanical Engineering",
"Established" : 1995,
"College" : "RGMCET",
"Located at": "Nandyal"
}
print(details.values())
for value in details.values():
print(value)
dict_values(['Mechanical Engineering', 1995, 'RGMCET', 'Nandyal'])
Mechanical Engineering
1995
RGMCET
Nandyal
Understanding dictionary functions
• all(): Returns True if all the keys of the dictionary are true, else false if the dictionary is empty
• dict1 = {1:'alpha', 2:'beta', 3:'gamma', 4:'music'}
• print(all(dict1)) *True
• dict2 = {1:'alpha', 2:'', '':'gamma', 4:'music'}
• print(all(dict2))

Department of Mechanical Engineering


59
RGM College of Engineering & Technology (Autonomous), Nandyal

• False
• any(): Returns True if any key of the dictionary is True else False, if the dictionary is empty.
• dict2 = {1:'alpha', 2:'', '':'gamma', 4:'music'}
• print(any(dict2))
• True
• len()
• This function calculates the length i.e., the number of * key:value pair elements in the dictionary
• dict1 = {1:'alpha', 2:'beta', 3:'gamma', 4:'music'}
• print(len(dict1))
• 4
• sorted()
• This function returns a new sorted list of keys in the * dictionary.
• dict1 = {2:'alpha', 3:'beta', 1:'gamma', 4:'music', 6:'video'}
• sortlist = sorted(dict1)
• print(sortlist)
• [1, 2, 3, 4, 6]
Understand the Methods in Dictionary
1. clear()
• This method is used to remove all the items from a given Python Dictionary.
• Syntax: dict.clear()
#Dictionary
#Containing marks data
marks = {
"Gurmeet": 100,
"Simran" : 95,
"Manmeet" : 93,
"Chetan" : 85,
"Sheila" : 89
}

print("Dictionary:",marks)

#Removing all items using clear()


marks.clear()

print("Empty Dictionary:", marks)

Department of Mechanical Engineering


60
RGM College of Engineering & Technology (Autonomous), Nandyal

Dictionary: {'Gurmeet': 100, 'Simran': 95, 'Manmeet': 93, 'Chetan': 85, 'Sheila': 89}
Empty Dictionary: {}
2. copy()
• This method is used to create a shallow copy of a given Python Dictionary.
dict1 = {
"Apple" : "Fruit",
"Banana" : "Fruit",
"Tomato" : "Vegetable",
"Papaya" : "Fruit",
"Potato" : "Vegetable"
}

dict2 = dict1.copy()

print("Orignal Dictionary:", dict1)


print("Copied Dictionary:", dict2)
Orignal Dictionary: {'Apple': 'Fruit', 'Banana': 'Fruit', 'Tomato': 'Vegetable', 'Papaya': 'Fruit', 'Potato':
'Vegetable'}
Copied Dictionary: {'Apple': 'Fruit', 'Banana': 'Fruit', 'Tomato': 'Vegetable', 'Papaya': 'Fruit', 'Potato':
'Vegetable'}
Example 2. Why you should not use = operator to create a dictionary copy?
dict1 = {
"Apple" : "Fruit",
"Banana" : "Fruit",
"Tomato" : "Vegetable",
"Papaya" : "Fruit",
"Potato" : "Vegetable"
}

#Using = operator for referring the dict1 to another variable dict2


dict2 = dict1

print("dict1:", dict1)
print("dict2:", dict2)

#Clearing the dict2 using clear()


dict2.clear()

#dict1 also got cleared


print("dict1:", dict1)
print("dict2:", dict2)

Department of Mechanical Engineering


61
RGM College of Engineering & Technology (Autonomous), Nandyal

dict1: {'Apple': 'Fruit', 'Banana': 'Fruit', 'Tomato': 'Vegetable', 'Papaya': 'Fruit', 'Potato': 'Vegetable'}
dict2: {'Apple': 'Fruit', 'Banana': 'Fruit', 'Tomato': 'Vegetable', 'Papaya': 'Fruit', 'Potato': 'Vegetable'}
dict1: {}
dict2: {}
dict1 = {
"Apple" : "Fruit",
"Banana" : "Fruit",
"Tomato" : "Vegetable",
"Papaya" : "Fruit",
"Potato" : "Vegetable"
}

#Using copy() method for copying the dict1 to another variable dict1
dict2 = dict1.copy()

print("dict1:", dict1)
print("dict2:", dict2)

#Clearing the dict2 using clear()


dict2.clear()

#Only dict1 got cleared


#dict1 remains unchanged
print("dict1:", dict1)
print("dict2:", dict2)
dict1: {'Apple': 'Fruit', 'Banana': 'Fruit', 'Tomato': 'Vegetable', 'Papaya': 'Fruit', 'Potato': 'Vegetable'}
dict2: {'Apple': 'Fruit', 'Banana': 'Fruit', 'Tomato': 'Vegetable', 'Papaya': 'Fruit', 'Potato': 'Vegetable'}
dict1: {'Apple': 'Fruit', 'Banana': 'Fruit', 'Tomato': 'Vegetable', 'Papaya': 'Fruit', 'Potato': 'Vegetable'}
dict2: {}
Now, here you see, when we have used the copy() method to create a new copy of the dictionary, the
variable dict2 now stores a separate copy of the dict1 at a separate memory address. Hence, any action
performed on either of the dictionaries should not affect the other dictionary.
As we’ve applied the clear() method only on dict2 here, only the dict2 is cleared, the dict1 remains
unchanged.
3.fromkeys(sequence, value)
The dict.fromkeys() method is used to create a new dictionary from a given sequence of keys and a
defined value by the user.
• newDict = dict.fromkeys(keys, value)

Department of Mechanical Engineering


62
RGM College of Engineering & Technology (Autonomous), Nandyal

Generating a dictionary only from a given sequence of Keys


#Defined Sequence of Keys
keys = ["name", "gender", "age", "website"]

#Creating a new Dictionary from Keys Sequence


bio = dict.fromkeys(keys)

print(bio)
{'name': None, 'gender': None, 'age': None, 'website': None}
Creating a dictionary from a given sequence of Keys & a fixed Value
#Defined Sequence of Keys
keys = ["name", "gender", "age", "website"]

#value to be assigned to each of dictionary key item


value = "Hello"

#Creating a new Dictionary from Keys Sequence


bio = dict.fromkeys(keys, value)

print(bio)
{'name': 'Hello', 'gender': 'Hello', 'age': 'Hello', 'website': 'Hello'}
4. d.get(key,defaultvalue)
• If the key is available then returns the corresponding value otherwise returns default value.
bio = {
"name" : "Gurmeet Singh",
"gender" : "MALE",
"age" : 21,
"website" : "wtmatter.com"
}

#Fetching key value (key exists)


print("Name:",bio.get("name"))

#Fetching key value (key do not exist)


print("Address:",bio.get("address"))

#Fetching key value (key exists)


#Value Argument Defined
print("Age:",bio.get("age", "Key not found!"))

#Fetching key value (key do not exist)

Department of Mechanical Engineering


63
RGM College of Engineering & Technology (Autonomous), Nandyal

#Value Argument Defined


print("Phone:",bio.get("phone", "Key not found!"))
Name: Gurmeet Singh
Address: None
Age: 21
Phone: Key not found!
5. items()
The method dict.items() returns a collection object containing the list of tuples such that each tuple
contains the dictionary items key & value pairs. Let’s say a dictionary contains 5 different key-value
pairs. Then this method applied to this dictionary will return dict_list collection object that will contain
five tuples. Each of these tuples will contain exactly two items, the first item will the key and the second
will be the value associated with that particular key.
#A Dictionary containing 4 items (key-value) pairs
bio = {
"name" : "Gurmeet Singh",
"gender" : "MALE",
"age" : 21,
"website" : "wtmatter.com"
}

#Using the items() method


items = bio.items()

print(items)
dict_items([('name', 'Gurmeet Singh'), ('gender', 'MALE'), ('age', 21), ('website', 'wtmatter.com')])
Modifying the dictionary after using the method items()
#A Dictionary containing 4 items (key-value) pairs
bio = {
"name" : "Gurmeet Singh",
"gender" : "MALE",
"age" : 21,
"website" : "wtmatter.com"
}

#Using the items() method


items = bio.items()

print("Before Modification", items)

#Modifying the original dictionary after using the items() method

Department of Mechanical Engineering


64
RGM College of Engineering & Technology (Autonomous), Nandyal

bio["country"] = "India"

print("After Modification", items)


Before Modification dict_items([('name', 'Gurmeet Singh'), ('gender', 'MALE'), ('age', 21), ('website',
'wtmatter.com')])
After Modification dict_items([('name', 'Gurmeet Singh'), ('gender', 'MALE'), ('age', 21), ('website',
'wtmatter.com'), ('country', 'India')])
6. Python Dictionary keys()
• The method dict.keys() is used to return a list of keys present in a given dictionary as a view object.
This view object is dict_keys.
Fetching the list of keys in a Dictionary
#A Dictionary with 4 items
bio = {
"name": "Gurmeet Singh",
"age" : 21,
"gender" : "MALE",
"country" : "India"
}

#Fetching Dictionary keys using keys() method


keysList = bio.keys()

print("List of Keys in bio:", keysList)


List of Keys in bio: dict_keys(['name', 'age', 'gender', 'country'])
7. Python Dictionary setdefault()
• The method dict.setdefault() is used to fetch the value for a key in a given dictionary and if the key
does not exist in the dictionary, this method will insert a default value for that particular key.
• Syntax: key_value = dict.setdefault(key, default_value)
#Working of setdefault() if the key is present in the Dictionary
#A Dictionary with 4 items
bio = {
"name": "Gurmeet Singh",
"age" : 21,
"gender" : "MALE",
"country" : "India"
}

#key exists
#only key argument passed
value = bio.setdefault("age")

Department of Mechanical Engineering


65
RGM College of Engineering & Technology (Autonomous), Nandyal

print("Value Returned:", value)


print("Dictionary bio:", bio)

#key exists
#both arguments passed
value = bio.setdefault("age", 25)

print("Value Returned:", value)


print("Dictionary bio:", bio)
Value Returned: 21
Dictionary bio: {'name': 'Gurmeet Singh', 'age': 21, 'gender': 'MALE', 'country': 'India'}
Value Returned: 21
Dictionary bio: {'name': 'Gurmeet Singh', 'age': 21, 'gender': 'MALE', 'country': 'India'}
#Working of setdefault() if the key is not present in the Dictionary
#A Dictionary with 4 items
bio = {
"name": "Gurmeet Singh",
"age" : 21,
"gender" : "MALE",
"country" : "India"
}

#key not exists


#only key argument passed
value = bio.setdefault("website")

print("Value Returned:", value)


print("Dictionary bio:", bio)

#key not exists


#both arguments passed
value = bio.setdefault("height", "180cms")

print("Value Returned:", value)


print("Dictionary bio:", bio)
Value Returned: None
Dictionary bio: {'name': 'Gurmeet Singh', 'age': 21, 'gender': 'MALE', 'country': 'India', 'website': None}
Value Returned: 180cms
Dictionary bio: {'name': 'Gurmeet Singh', 'age': 21, 'gender': 'MALE', 'country': 'India', 'website': None,
'height': '180cms'}

Department of Mechanical Engineering


66
RGM College of Engineering & Technology (Autonomous), Nandyal

8. Python Dictionary update()


The method dict.update() is used to add new items to a given dictionary using another Python Dictionary
object or such an iterable object that contains (key, value) pair based items.
Note. The new items from another dictionary or iterable are added as it is in case their keys are already
not present in the dictionary on which the method is applied. But in case, the dictionary already contains
the same key(s), the key(s) values get updated with the value(s) from the new dictionary or iterable.
#Adding more items from another dictionary using the method
items = {
"India" : "INR",
"USA" : "USD",
"Canada" : "CAD",
"Italy" : "EUR"
}

moreItems = {
"Japan" : "JPY",
"Brazil" : "BRL"
}

print("Initial Items:", items)

#Adding Items from moreItems into items


items.update(moreItems)

print("Updated Items:", items)


Initial Items: {'India': 'INR', 'USA': 'USD', 'Canada': 'CAD', 'Italy': 'EUR'}
Updated Items: {'India': 'INR', 'USA': 'USD', 'Canada': 'CAD', 'Italy': 'EUR', 'Japan': 'JPY', 'Brazil':
'BRL'}
#Adding items from a (key, value) pair based Iterable
items = {
"India" : "INR",
"USA" : "USD",
"Canada" : "CAD",
"Italy" : "EUR"
}

#An Iterable containing (key, value) pair-based items


moreItems = [
("Japan", "JPY"),
("Brazil", "BRL")
]

Department of Mechanical Engineering


67
RGM College of Engineering & Technology (Autonomous), Nandyal

print("Initial Items:", items)

#Adding Items from moreItems into items


items.update(moreItems)

print("Updated Items:", items)


Initial Items: {'India': 'INR', 'USA': 'USD', 'Canada': 'CAD', 'Italy': 'EUR'}
Updated Items: {'India': 'INR', 'USA': 'USD', 'Canada': 'CAD', 'Italy': 'EUR', 'Japan': 'JPY', 'Brazil':
'BRL'}
#Working of update() without iterables
items = {
"Hello" : 0,
"," : 1,
"How" : 2,
"are" : 3,
}

print("Initial Items:", items)

items.update(you = 4, Gurmeet = 5)

print("Updated Items:", items)


Initial Items: {'Hello': 0, ',': 1, 'How': 2, 'are': 3}
Updated Items: {'Hello': 0, ',': 1, 'How': 2, 'are': 3, 'you': 4, 'Gurmeet': 5}
9. Python Dictionary values()
The method dict.values() is used to get the view object that contains the list of all of the values of a given
dictionary. This method fetches the values from all of the key, value pair items in the dictionary and show
them as a collection object known as the dict_values object.
#Fetching values form a given Dictionary using the method values()
#A Dictionary of languages
languages = {
0 : "English",
1 : "Hindi",
2 : "Punjabi",
3 : "Spanish",
4 : "French"
}

#Getting only Dictionary Values using values()


values = languages.values()

Department of Mechanical Engineering


68
RGM College of Engineering & Technology (Autonomous), Nandyal

print("Values:", values)
Values: dict_values(['English', 'Hindi', 'Punjabi', 'Spanish', 'French'])
#dict_values gets updated if the dictionary is updated
#A Dictionary of languages
languages = {
0 : "English",
1 : "Hindi",
2 : "Punjabi",
3 : "Spanish",
4 : "French"
}

#Getting only Dictionary Values using values()


values = languages.values()

print("Values Before Adding More Items:", values)

#Adding more Dictionary items


languages[5] = "Tamil"
languages[6] = "Telegu"

print("Values After Adding More Items:", values)


Values Before Adding More Items: dict_values(['English', 'Hindi', 'Punjabi', 'Spanish', 'French'])
Values After Adding More Items: dict_values(['English', 'Hindi', 'Punjabi', 'Spanish', 'French', 'Tamil',
'Telegu'])
10. Python Dictionary pop()
The method dict.pop() is used to remove a particular element from a given dictionary by its key and this
method also returns the removed item value.
#Removing the Item from the dictionary using pop(), if the key exists
#A Dictionary of 5 items
items = {
"Brinjal (Eggplant)" : "Vegetable",
"Onion" : "Vegetable",
"Papaya" : "Fruit",
"Mango" : "Fruit",
"Radish" : "Vegetable"
}
print('before pop : ', items)

#Popping the item with key Papaya

Department of Mechanical Engineering


69
RGM College of Engineering & Technology (Autonomous), Nandyal

value = items.pop("Papaya")

print("items:", items)
print("Returned Value:", value)
before pop : {'Brinjal (Eggplant)': 'Vegetable', 'Onion': 'Vegetable', 'Papaya': 'Fruit', 'Mango': 'Fruit',
'Radish': 'Vegetable'}
items: {'Brinjal (Eggplant)': 'Vegetable', 'Onion': 'Vegetable', 'Mango': 'Fruit', 'Radish': 'Vegetable'}
Returned Value: Fruit
#Working of pop() if the key does not exist
#A Dictionary of 5 items
items = {
"Brinjal (Eggplant)" : "Vegetable",
"Onion" : "Vegetable",
"Papaya" : "Fruit",
"Mango" : "Fruit",
"Radish" : "Vegetable"
}

#Popping the item with key Banana


#Item with this key not present in the dictionary
value = items.pop("Banana")

print("items:", items)
print("Returned Value:", value)
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-51-d120b4ccf672> in <module>()
11 #Popping the item with key Banana
12 #Item with this key not present in the dictionary
---> 13 value = items.pop("Banana")
14
15 print("items:", items)

KeyError: 'Banana'
#If the key does not exist in the dictionary but the default argument is passed
#A Dictionary of 5 items
items = {
"Brinjal (Eggplant)" : "Vegetable",
"Onion" : "Vegetable",
"Papaya" : "Fruit",
"Mango" : "Fruit",
"Radish" : "Vegetable"

Department of Mechanical Engineering


70
RGM College of Engineering & Technology (Autonomous), Nandyal

#Popping the item with key Banana


#Item with this key not present in the dictionary
#Value of default is also passed
value = items.pop("Banana", "Fruit")

print("items:", items)
print("Returned Value:", value)
items: {'Brinjal (Eggplant)': 'Vegetable', 'Onion': 'Vegetable', 'Papaya': 'Fruit', 'Mango': 'Fruit', 'Radish':
'Vegetable'}
Returned Value: Fruit
11. Python Dictionary popitem()
The method dict.popitem() is used to remove the last inserted item from a given Python Dictionary as of
version 3.7 & above. In the earlier versions, this method removes a random (arbitrary) item from the
dictionary.
Note. The last item displaying in a Python Dictionary may not be the actual last inserted item.
#Working of popitem() method
#A Dictionary with 4 items
bio = {
"name": "Gurmeet Singh",
"age" : 21,
"gender" : "MALE",
"country" : "India"
}

print("Before Last Insertion, bio:", bio)

#last item insertion


bio["website"] = "wtmatter.com"

print("After Insertion, bio:", bio)

bio.popitem()

print("After Popping, bio:", bio)


Before Last Insertion, bio: {'name': 'Gurmeet Singh', 'age': 21, 'gender': 'MALE', 'country': 'India'}
After Insertion, bio: {'name': 'Gurmeet Singh', 'age': 21, 'gender': 'MALE', 'country': 'India', 'website':
'wtmatter.com'}
After Popping, bio: {'name': 'Gurmeet Singh', 'age': 21, 'gender': 'MALE', 'country': 'India'}
12.len()
This method returns the length.

Department of Mechanical Engineering


71
RGM College of Engineering & Technology (Autonomous), Nandyal

dict = {'Name': 'Zara', 'Age': 7};


print ("Length : %d" % len (dict))
Length : 2
Dictionary Comprehensions
• Dictionary comprehension is a method for transforming one dictionary into another dictionary.
During this transformation, items within the original dictionary can be conditionally included in the
new dictionary and each item can be transformed as needed.
• Dictionary Comprehensions return output in Dictionary format like (key : value) pairs and Keys
should be unique and each key has a respective value.
– {key : value for (key , value) in iterable}
squares={x:x*x for x in range(1,6)}
print(squares)
doubles={x:2*x for x in range(1,6)}
print(doubles)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10}

Ex: Python Program to Count the Number of Each Vowel

# Program to count the number of each vowels


# string of vowels
vowels = 'aeiou'
ip_str = 'Hello, have you tried our tutorial section yet?'
# make it suitable for caseless comparisions
ip_str = ip_str.casefold()
# make a dictionary with each vowel a key and value 0
count = {}.fromkeys(vowels,0)
# count the vowels
for char in ip_str:
if char in count:
count[char] += 1
print(count)
output:
{'o': 5, 'i': 3, 'a': 2, 'e': 5, 'u': 3}

Department of Mechanical Engineering


72

You might also like