PWP Chapter 3
PWP Chapter 3
Unit No. 3
Data Structures in Python
by
P. S. Bhandare
Hours: 12
Marks: 14
1|Page
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
Syllabus:
3.1 Lists:
a) Defining lists, accessing values in list, deleting values in list, updating lists.
b) Basic List Operations
c) Built-in List functions
3.2 Tuples:
a) Accessing values in Tuples, deleting values in Tuples, and updating Tuples.
b) Basic Tuple operations.
c) Built-in Tuple functions
3.3 Sets:
a) Accessing values in Set, deleting values in Set and updating Sets.
b) Basic Set operations.
c) Built-in Set functions
3.4 Dictionaries:
a) Accessing values in Dictionary, deleting values in Dictionary and updating
Dictionary.
b) Basic Dictionary operations.
c) Built-in Dictionaries functions
2|Page
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
The title of chapter data structures in python says that this chapter
includes basic data structures needed to do programming in python
language.
Also, it includes operations performed on data structures of python
programming language.
Outcomes of Chapter:
3a. Write python program to use and manipulate lists for the given
problem.
3b. Write python program to use and manipulate Tuples for the given
problem.
3c. Write python program to use and manipulate Sets for the given
problem.
3d. Write python program to use and manipulate Dictionaries for the
given problem.
3|Page
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
Introduction
1. List
A list is similar to an array that consists of a group of elements or items. Just
like an array, a list can store elements. But, there is one major difference
between an array and a list. An array can store only one type of elements
whereas a list can store different types of elements. Hence lists are more
versatile and useful than an array. Perhaps lists are the most used datatype
in Python programs.
We need other information about the student, like his roll number, name,
gender along with his marks. So, the information looks like this:
Here, we have different types of data. Roll number (10) is an integer. Name
('Poly tech’) is a string. Gender ('M') is a character and the marks (50, 55,
62, 74, 66) are again integers. In daily life, generally we have this type of
information that is to be stored and processed. This type of information
cannot be stored in an array because an array can store only one type of
elements. In this case, we need to go for list datatype. A list can store
different types of elements. To store the student's information discussed so
far, we can create a list as:
student= [10, 'Poly tech', ‘M’ ,50,55,62,74,66]
4|Page
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
Please observe that the elements of the 'student' list are stored in square
braces []. We can create an empty list without any elements by simply
writing empty square braces as:
Thus we can create a list by embedding the elements inside a pair of square
braces []. The elements in the list should be separated by a comma (, ). To
view the elements of a list as a whole, we can simply pass the list name to
the print() function as:
print(student)
print(student[1])
print(student [0:3:1])
The elements are given below:
[10, ‘Poly tech’, 'M']
5|Page
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
Here, since we did not mention the starting element position, it will start at
0 and stepsize will be taken as 1. Suppose, we do not mention anything in
slicing, then the total list will be extracted as:
print(student[::])
it will display list as: [10, ‘Poly tech’, 'M', 50, 55, 62, 74, 66]
Apart from indexing and slicing, the 5 basic operations: finding length,
concatenation, repetition, membership and iteration operations can be
performed on lists and other sequences like strings, tuples or dictionaries.
In the following program, we are creating lists with different types of
elements and also displaying the list elements.
6|Page
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
In fact, the range() function does not return list of numbers. It returns only
range class object that stores the data about 'start', 'stop' and 'stepsize'. For
example, if we write:
print(range (4, 9, 2)
The preceding statement will display: range (4, 9, 2) # this is the object
given by range().
This range object should be used in for loop to get the range of numbers
desired by the programmer. For example:
for i in range(4,9,2)
print(i)
The preceding statement will display 4, 6, 8. Hence, we say range object is
'iterable', that is, suitable as a target for functions and loops that expect
something from which they can obtain successive items. For example, range
object can be used in for loops to display the numbers, or with list()
function to create a list. In the following example, the range() function is
used in the list() function to create a list:
lst = list (range(4,9,2))
print (lst)
7|Page
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
The list is shown below: [4, 6.8] If we are not using the list() function and
using range() alone to create a list, then we will have only range class object
returned by the range() function. For example,
lst=range (4, 9, 2)
print (lst)
it is range object In this case, using a loop like for or while is necessary to
view the elements of the list. For example,
for i in lst:
print(i)
will display 4, 6, 8.
We can use while loop or for loop to access elements from a list. The len()
function is useful to know the number of elements in the list. For example,
len(list) gives total number of elements in the list. The following while loop
retrieves starting from Oth to the last element of the list:
8|Page
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
Observe the len(list) function in the while condition as: while i<len(list).
This will return the total number of elements in the list. If the total number
of elements is 'n', then the condition will become: while(i<n). It means i
values are changing from 0 to n-1. Thus this loop will display all elements of
the list from 0 to n-1.
Here, 'i' will assume one element at a time from the list and hence if we
display 'i' value, it will display the elements one by one.
Lists are mutable. It means we can modify the contents of a list. We can
append, update or delete the elements of a list depending upon our
requirements.
Appending an element means adding an element at the end of the list. To
append a new element to the list, we should use the append() method. In
the following example, we are creating a list with elements from 1 to 4 and
then appending a new element 9.
9|Page
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
Updating an element means changing the value of the element in the list.
This can be done by accessing the specific element using indexing or slicing
and assigning a new value. Consider the following statements:
lst[1:3] = 10, 11
print(lst) #update 1st and 2nd elements of lst
The preceding statements will give:
[1, 10, 11, 4, 9]
Deleting an element from the list can be done using 'del' statement. The del
statement takes the position number of the element to be deleted.
We can also delete an element using the remove() method. In this method,
we should pass the element to be deleted.
lst.remove(11)
print(lst) # delete 11 from lst
Now, the list appears as:
[1, 4, 9]
Elements of a list can be reversed easily by using the reverse() method, as:
list.reverse()
This will reverse the order of elements in the list and the reversed elements
are available in the list. Suppose, we do not have the reverse() method, then
how can we develop logic to display the elements in reverse order? This can
be done using while loop and accessing the elements in reverse order. For
10 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
i = - 1 # last element
while i >= - 5 # display from -1th to -5th elements
print(days[i])
i -=1 #decrease the position every time.
We can simply use '+' operator on two lists to join them. For example, x' and
'y' are two lists. If we write x+y, the list 'y' is joined at the end of the list 'x'.
x =[ 10,20,30,40,5]
y=[100,110,120 ]
print(x+y)
The concatenated list appears: [10, 20, 30, 40, 50, 100, 110, 120]
Repetition of Lists
We can repeat the elements of a list 'n' number of times using " operator.
For example, if we write x'n, the list 'x' will be repeated for n times as:
print( x ^ * 2) #repeat the list x for 2 times
Now, the list appears as: [10, 20, 30, 40, 50, 10, 20, 30, 40, 50]
11 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
Membership in Lists
We can check if an element is a member of a list or not by using 'in' and 'not
in' operator. If the element is a member of the list, then 'in' operator returns
True else False. If the element is not in the list, then 'not in' operator
returns True else False. See the examples below:
Hence, if the programmer wants two independent lists, he should not go for
aliasing. On the other hand, he should use cloning or copying.
Obtaining exact copy of an existing object (or list) is called 'cloning'. To
clone a list, we can take help of the slicing operation as:
y =x[:] # x is cloned as y
12 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
When we clone a list like this, a separate copy of all the elements is stored
into ‘y'. The lists ‘x' and 'y' are independent lists. Hence, any modifications
to 'x' will not affect ‘y' and vice versa. Consider the following statements:
x = [10,20,30,40,50]
y = x[:] # x is cloned as y
print(x) will display [10,20,30,40,50]
print(y) will display [10,20,30,40,50]
x[1] = 99 # modify 1st element in x
print(x) #will display [10,99,30,40,50]
print(y) # will display [10,20,30,40,50]
y = x.copy() # x is copied as y
When we copy a list like this, a separate copy of all the elements is stored
into ‘y'. The lists 'x' and 'y' are independent. Hence, any modifications to 'x'
will not affect ‘y' and vice versa.
Operations on list:
1. Append()
As we know, a list is mutable. We can add an element at the back of the list
using an inbuilt function of Python list operation append(). Let us see
implementations of it.
my_list=[1,2,3]
my_list.append(9)
my_list.append(8)
print("The list after append() operation is: ",my_list)
Here, we created a list called my_list and added elements to the list. The output of the
above code is:
Output:
2. extend()
Extend () method can be used to add more than one element at the end of a list. Let us
understand the function by its implementation.
my_list.extend([20,21])
13 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
By entering the values in a square bracket inside the function extend, we can see that all
the elements are added to the list.
3. Insert()
Now we can insert an element in between the list using the inbuilt function of Python
list operation insert()
my_list.insert(5,30)
print("The list after insert() operator is: \n",my_list)
In this function, the first input is the position at which the element is to be added, and
the second input is the element's value. Here after using the insert() we have added 30
at 5th position in my_list. Hence the updated list will be:
4. remove()
The way we added an element between the list, similarly, we can remove from in
between a list using an inbuilt Python list operation function remove().
my_list.remove(10)
print("The list after remove() operator is: \n",my_list)
As we have removed 10 from my_list, the output of the above code will be:
After using pop() operator, the last element would be removed from our my_list list.
Here the last element, 5, is removed from the list. Hence our updated list is
6. Slice()
This method is used to print a section of the list. Which means we can display elements
of a specific index.
print("The elements of list in the range of 3 to 12 are:\n",my_list[3:12])
Using the slicing operator, we have sliced elements from range of 3 to 12 in the my_list.
Hence the above code would print elements whose index lies between the range 3 to
12.
Note that the slice method only prints the elements; it does not change the list.
14 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
7. reverse()
To reverse the indexing of elements in a list, the simple built-in function reverse() can
be used. This function allows the user to reverse the order of elements very quickly and
without large code lines. To reverse a list, it needs to be parsed with the function itself.
Example:
coding_list = ["coding", "ninjas”, "data", "science"]
coding_list.reverse() #Reverse Function implemented
print(coding_list)
Output:
['science', 'data', 'ninjas', 'coding']
8. len(), min() & max()
Other Python list operations are len(), min(), and max(). As the name suggests, they
are used to know the length of a list, the minimum element in the list, and the maximum
element in the list, respectively.
print("Length of the list is: ",len(my_list))
print("Maximum element in the list is: ",max(my_list))
print("Minimum element in the list is: ",min(my_list))
9. count()
As we can store duplicates in a list, a Python list operation is used to count the number
of copies, known as count().
my_list.extend([10,20,22])
print("The list is: \n",my_list)
print("Number of times 20 is in the list are: ",my_list.count(20))
After using the extend() and count() operator on my_list, the the number of repetitions
of 21 are:
15 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
string_one = ["Coding"]
string_two = ["Ninjas"]
new_string = string_one + string_two
print(new_string)
Output:
11. Multiply
Did you know that you can increase the number of elements in a list by simply
multiplying it by a number? For example, by multiplying a list with the number ‘n’, you
get that list element being repeated ‘n’ times. List multiplication can be performed by
just using the “*” operator. Following is a code example:
Example:
list_one = [100, 150, 200]
list_two = list_one * 3 #Multiplied the list with 3
print(list_two)
Output:
12. index()
index() is a built-in Python function that lets users access the elements of a list, tuple,
or string. This is a really useful function, especially when the data inside the list or tuple
is very large. Note that if there are duplicate entries in the list, tuple, or string, then the
first occurrence of that particular element will be represented in the output.
Example:
list_one = [100, 150, 200]
print(list_one.index(100)) #Using index function for a list
Output:
13. sort()
The most used function while using a list is sort(). With the help of the function, we can
sort the list(my_list) in ascending order.
Python
my_list=[8,10,4,1,3,19,11,9,20]
my_list.sort()
print("The list after sort() operator is: \n",my_list)
We can see the sorted my_list as the output.
So far, we've seen various Python list operations using inbuilt functions. Now let us look
at some arithmetic and logical operations in lists.
14. clear()
If you want to clear all the elements present in a list, set, or dictionary, then clear() is
one of the most efficient and easy built-in functions to use. It is important to note that
16 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
this can be implemented on a list, set, or dictionary only. Using this function, you can
clear all the contents, and the result is None.
Example:
list_one = [100, 150, 200]
list_one.clear() #This clears all the elements present in the list
print(list_one)
Output:
List Methods
Function Description
extend() Adds more than one element to the end of the list
17 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
x=[]
n=int(input("Enter how many element: "))
for i in range(n):
ele=int(input("Enter element to add to list: "))
x.append(ele)
print("List= ",x)
ele=int(input("Enter element to count: "))
18 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
c=0
for i in x:
if i==ele:
c+=1
print("%d element found %i times"%(ele,c))
"""
o/p:
Enter how many element: 7
Enter element to add to list: 11
Enter element to add to list: 22
Enter element to add to list: 33
Enter element to add to list: 11
Enter element to add to list: 22
Enter element to add to list: 22
Enter element to add to list: 33
List= [11, 22, 33, 11, 22, 22, 33]
Enter element to count: 22
22 element found 3 times
"""
"""
o/p:
Common= [66, 44, 77, 22]
"""
Nested List:
A list within another list is called a nested list. We know that a list contains
several elements. When we take a list as an element in another list, then that list
is called a nested list. For example
b=[10, 20, 30, [80, 90]]
19 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
The last element [80, 90] represents a nested list. So, 'b' has 4 elements and they
are:
b[0] = 10
b[1] = 20
b[2] = 30
b[3] =[80, 90]
So, b[3] represents the nested list and if we want to display its elements
separately, we can use a for loop as:
for x in b[3] :
print(x)
Tuple
A tuple is a Python sequence which stores a group of elements or items. Tuples
are similar to lists but the main difference is tuples are immutable whereas lists
are mutable. Since tuples are immutable, once we create a tuple we cannot
modify its elements. Hence we cannot perform operations like append(),
extend(), insert(), remove(), pop() and clear() on tuples. Tuples are generally
used to store data which should not be modified and retrieve that data on
demand.
Creating Tuples
We can create a tuple by writing elements separated by commas inside
parentheses (). The elements can be of same datatype or different types. For
example, to create an empty tuple, we can simply write empty parenthesis, as:
tup1 = ()# empty touple
If we want to create a tuple with only one element, we can mention that element
in parentheses and after that a comma is needed, as:
tup2 = (10,) # tuple with one element. observe comma after the element.
Here is a tuple with different types of elements:
tup3= (10, 20, 30.1, 40.5, 'Hyderabad', 'New Delhi')
We can create a tuple with only one of type of elements also, like the following:
tup4 =(10, 20, 30) # tuple with integers
If we do not mention any brackets and write the elements separating them by
commas, then they are taken by default as a tuple. See the following example:
tup5 = 1, 2, 3, 4 #no braces
The point to remember is that if do not use any brackets, it will become a tuple
and not a list or any other datatype.
It is also possible to create a tuple from a list. This is done by converting a list into
a tuple using the tuple() function. Consider the following example:
list = [1, 2, 3] #take a list
tul=tuple(list) #convert list into tuple
print(tpl)
20 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
print(tup [- 1] )
The preceding statement will give:100
If you write,
print (tup[- 6])
Then the following element appears: 50
Slicing represents extracting a piece or part of the tuple. Slicing is done in the
format: [start: stop: stepsize). Here, 'start' represents the position of the starting
element and 'stop' represents the position of the ending element and the
'stepsize' indicates the incrementation. If the tuple contains n' elements, the
default values will be o for 'start' and n-1 for 'stop' and 1 for 'stepsize'. For
example, to extract all the elements from the tuple, we can write:
print(tup[:])
The elements of tuple appear: (50, 60, 70, 80, 90, 100)
For example, to extract the elements from 1 to 4th, we can write:
print(tup[1:4])
The elements of tuple appear: (60, 70, 80)
Similarly, to extract every other element, i.e. alternate elements, we can write:
21 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
22 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
23 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
Tuple Functions:
1) len() :
The len() function is used to return the number of elements in a tuple. It
takes a tuple as an argument and returns an integer value representing the
length of the tuple.
my_tuple = (1, 2, 3, 4, 5)
print(len(my_tuple))
Output: 5
2) max():
The max() function is used to return the maximum value in a tuple. It takes
a tuple as an argument and returns the maximum value in the tuple.
my_tuple = (5, 6, 7, 8, 9)
24 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
print(max(my_tuple))
Output: 9
3) min():
The min() function is used to return the minimum value in a tuple. It takes
a tuple as an argument and returns the minimum value in the tuple.
my_tuple = (5, 6, 7, 8, 9)
print(min(my_tuple))
Output: 5
4) sum():
The sum() function is used to return the sum of all elements in a tuple. It
takes a tuple as an argument and returns the sum of all the elements in the
tuple.
my_tuple = (1, 2, 3, 4, 5)
print(sum(my_tuple))
Output: 15
5) tuple():
The tuple() function is used to create a tuple from a list, set, or any iterable
object. It takes an iterable object as an argument and returns a tuple
containing all the elements in the iterable object.
my_list = [1, 2, 3, 4, 5]
my_tuple = tuple(my_list)
print(my_tuple)
Output: (1, 2, 3, 4, 5)
6) index():
It returns the index of the first occurrence of a specified element in a tuple.
fruits = ('apple', 'banana', 'orange', 'mango', 'banana')
# Find the index of 'orange'
index = fruits.index('orange')
print(index)
Output: 2
7) count():
It returns the number of times a specified element appears in a tuple.
my_tuple = (1, 2, 3, 4, 3, 5, 3)
# Count the number of times the element '3' occurs in the tuple
count = my_tuple.count(3)
print(count)
Output: 3
25 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
Updating Tuple:
Although tuples are immutable, you can concatenate them using the + operator.
In this process, the original object remains unchanged, and a new object is
created.
1. Using concat operator
t = (0, 1, 2)
t_add = t + (3, 4, 5)
print(t_add)
# (0, 1, 2, 3, 4, 5)
print(t)
# (0, 1, 2)
2. Elements can be inserted as following way also:
a=(1,2,3,5,6)
a=a[:3]+(4,)+a[3:]
print(a)
output: (1, 2, 3, 4, 5, 6)
3. Converting into list
my_tuple = ('a', 'b', 'c')
my_list = list(my_tuple)
my_list.insert(3, 'd')
new_tuple = tuple(my_list)
print(new_tuple)
output: ('a', 'b', 'c', 'd')
t=(11,22,33,44,55,66,77,88,99)
p=int(input("Enter Position: "))
t1=t[0:p-1]
t=t1+t[p:]
print(t)
26 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
Set
Sets are used to store multiple items in a single variable. Set is one of 4
built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage. A set is a
collection which is unordered, unchangeable, and unindexed. Set are represented
by { } (values enclosed in curly braces) A Python set is the collection of the
unordered items. Each element in the set must be unique, immutable, and the
sets remove the duplicate elements. Sets are mutable which means we can
modify it after its creation.
Unlike other collections in Python, there is no index attached to the elements of
the set, i.e., we cannot directly access any element of the set by the index.
However, we can print them all together, or we can get the list of elements by
looping through the set.
e.g.
s={10,20,30,40,50,60,70}
Creating & Accessing Set:
1. Using curly braces:
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
"Sunday"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
2. Using set() method :
l1=[11,22,33,44,55,66,77,88]
s1=set(l1)
print(s1)
for i in s1:
print(i)
3. Using range function:
s1=set(range(0,10))
print(s1)
for i in s1:
27 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
print(i)
Creating an empty set is a bit different because empty curly {} braces are also
used to create a dictionary as well. So Python provides the set() method used
without an argument to create an empty set.
# Empty curly braces will create dictionary
set3 = {}
print(type(set3))
# Empty set using set() function
set4 = set()
print(type(set4))
Python provides the add() method and update() method which can be used to
add some particular item to the set. The add() method is used to add a single
element whereas the update() method is used to add multiple elements to the
set.
1. Using add() method:
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nAdding other months to the set...");
Months.add("July");
Months.add ("August");
print("\nPrinting the modified set...");
print(Months)
print("\nlooping through the set elements ... ")
for i in Months:
print(i)
28 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
Python provides the discard() method and remove() method which can be used
to remove the items from the set. The difference between these function, using
discard() function if the item does not exist in the set then the set remain
unchanged whereas remove() method will through an error.
1. Using discard() method
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.discard("January");
months.discard("May");
print("\nPrinting the modified set...");
print(months)
print("\nlooping through the set elements ... ")
for i in months:
print(i)
2. Using remove() function:
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.remove("January");
months.remove("May");
print("\nPrinting the modified set...");
print(months)
3. Using pop() method:
We can also use the pop() method to remove the item. Generally, the pop()
method will always remove the last item but the set is unordered, we can't
determine which element will be popped from set.
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving some months from the set...");
Months.pop();
Months.pop();
29 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
30 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
we can also make the union of more than two sets using the union() function, for
example:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}
# Find the common elements between the three sets
common_elements = set1.union(set2, set3)
# Print the common elements
print(common_elements)
The intersection of two sets:
To discover what is common between two or more sets in Python, apply the
intersection() function. Only the items in all sets being compared are included in
the final set. One or more sets can also be used as the intersection() function
parameters. The function returns a copy of the set supplied as the lone parameter
if there is just one set. The method returns a new set that only contains the
elements in all the compared sets if multiple sets are supplied as arguments.
The intersection of two sets can be performed by the and & operator or
the intersection() function. The intersection of the two sets is given as the set of
the elements that common in both sets.
Output:
{'Monday', 'Tuesday'}
set1 = {1,2,3,4,5,6,7}
set2 = {1,2,20,32,5,9}
set3 = set1.intersection(set2)
print(set3)
31 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
Output:
{1,2,5}
Similarly, as the same as union function, we can perform the intersection of more
than two sets at a time.
# Create three sets
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}
# Find the common elements between the three sets
common_elements = set1.intersection(set2, set3)
# Print the common elements
print(common_elements)
o/p: {3}
The intersection_update() method removes the items from the original set that are not
present in both the sets (all the sets if more than one are
specified).The intersection_update() method is different from the intersection()
method since it modifies the original set by removing the unwanted items, on the other
hand, the intersection() method returns a new set.
Output:
{'castle'}
Difference between the two sets
The difference of two sets can be calculated by using the subtraction (-) operator
or intersection() method. Suppose there are two sets A and B, and the difference is A-B
that denotes the resulting set will be obtained that element of A, which is not present in
the set B.
32 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
In Python, the symmetric Difference between set1 and set2 is the set of elements
present in one set or the other but not in both sets. In other words, the set of elements is
in set1 or set2 but not in their intersection.
33 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
Using ^ operator
a = {1,2,3,4,5,6}
b = {1,2,9,8,10}
c = a^b
print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
Example - 2: Using symmetric_difference() method
a = {1,2,3,4,5,6}
b = {1,2,9,8,10}
c = a.symmetric_difference(b)
print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
Set comparisons
In Python, you can compare sets to check if they are equal, if one set is a subset or
superset of another, or if two sets have elements in common.
o ==: checks if two sets have the same elements, regardless of their order.
o !=: checks if two sets are not equal.
o <: checks if the left set is a proper subset of the right set (i.e., all elements in the
left set are also in the right set, but the right set has additional elements).
o <=: checks if the left set is a subset of the right set (i.e., all elements in the left set
are also in the right set).
o >: checks if the left set is a proper superset of the right set (i.e., all elements in the
right set are also in the left set, but the left set has additional elements).
o >=: checks if the left set is a superset of the right set (i.e., all elements in the right
set are also in the left).
34 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
SN Method Description
4 difference_update(....) It modifies this set by removing all the items that are
also present in the specified sets.
7 intersection_update(....) It removes the items from the original set that are not
present in both the sets (all the sets if more than one
are specified).
35 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
Python Dictionary
Here, the name of the dictionary is 'dict'. The first element in the dictionary is
a string ‘Name'. So, this is called 'key'. The second element is 'Poly' which is
taken as its 'value'. Observe that the key and its value are separated by a
colon. Similarly, the next element is 'Id' which becomes 'key' and the next
element '200' becomes its value. Finally, 'Salary' becomes key and '9080.50'
becomes its value. So, we have 3 pairs of keys and values in this dictionary.
Dictionaries are a useful data structure for storing data in Python because
they are capable of imitating real-world data arrangements where a certain
value exists for a given key.
36 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
A dictionary is, in other words, a group of key-value pairs, where the values
can be any Python object. The keys, in contrast, are immutable Python objects,
such as strings, tuples, or numbers. Dictionary entries are ordered as of
Python version 3.7. In Python 3.6 and before, dictionaries are generally
unordered.
Curly brackets are the simplest way to generate a Python dictionary, although
there are other approaches as well. With many key-value pairs surrounded in
curly brackets and a colon separating each key from its value, the dictionary
can be built. (:). The following provides the syntax for defining the dictionary.
Syntax:
Dict = {"Name": "Polytech", "Age":35}
In the above dictionary Dict, The keys Name and Age are the strings which
comes under the category of an immutable object.
e.g.
Employee = {"Name": "Johnny", "Age": 32, "salary":26000,"Company":"^TCS"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
Python provides the built-in function dict() method which is also used to
create the dictionary. The empty curly braces {} is used to create empty
dictionary.
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Hcl', 2: 'WIPRO', 3:'Facebook'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)
37 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(4, 'Rinku'), (2, Singh)])
print("\nDictionary with each item as a pair: ")
print(Dict)
The dictionary is a mutable data type, and utilising the right keys allows you
to change its values. Dict[key] = value and the value can both be modified. An
existing value can also be updated using the update() method.
38 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
Program-2:
Deleting Elements:
The items of the dictionary can be deleted by using the del keyword.
Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ")
39 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
e.g.
# Creating a Dictionary
Dict1 = {1: 'JavaTpoint', 2: 'Educational', 3: 'Website'}
# Deleting a key
# using pop() method
pop_key = Dict1.pop(2)
print(Dict1)
Iterating Dictionary
40 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
#for loop to print the values of the dictionary by using values() method.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in Employee.values():
print(x)
#for loop to print the items of the dictionary by using items() method
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in Employee.items():
print(x)
In the dictionary, we cannot store multiple values for the same keys. If we pass
more than one value for a single key, then the value which is last assigned is
considered as the value of the key.
Employee={"Name":"John","Age":29,"Salary":25000,"Company":"WIPRO","Name"
: "John"}
for x,y in Employee.items():
print(x,y)
Dictionary Methods:
Method Description
items() Returns a list containing a tuple for each key value pair
41 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
setdefault() Returns the value of the specified key. If the key does not exist: insert the key,
with the specified value
o len()
The dictionary's length is returned via the len() function in Python. The string is
lengthened by one for each key-value pair.
Output: 4
o any()
Like how it does with lists and tuples, the any() method returns True indeed if
one dictionary key does have a Boolean expression that evaluates to True.
Output : True
o all()
Unlike in any() method, all() only returns True if each of the dictionary's keys
contain a True Boolean value.
42 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
Output : False
o sorted()
Like it does with lists and tuples, the sorted() method returns an ordered series
of the dictionary's keys. The ascending sorting has no effect on the original
Python dictionary.
Output : [ 1, 5, 7, 8]
The built-in python dictionary methods along with the description and Code are
given below.
o clear()
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# clear() method
dict.clear()
print(dict)
Output: { }
o copy()
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# copy() method
dict_demo = dict.copy()
print(dict_demo)
43 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
o pop()
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# pop() method
dict_demo = dict.copy()
x = dict_demo.pop(1)
print(x)
Output: {2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}
popitem()
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# popitem() method
dict_demo.popitem()
print(dict_demo)
Output :{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}
o keys()
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# keys() method
print(dict_demo.keys())
Output : dict_keys([1, 2, 3, 4, 5])
o items()
44 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# items() method
print(dict_demo.items())
Output : dict_items([(1, 'Hcl'), (2, 'WIPRO'), (3, 'Facebook'), (4, 'Amazon'), (5,
'Flipkart')])
o get()
It is used to get the value specified for the passed key.
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# get() method
print(dict_demo.get(3))
Output: Facebook
o update()
It mainly updates all the dictionary by adding the key-value pair of dict2 to this
dictionary.
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# update() method
dict_demo.update({3: "TCS"})
print(dict_demo)
Output : {1: 'Hcl', 2: 'WIPRO', 3: 'TCS'}
o values()
It returns all the values of the dictionary with respect to given input.
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# values() method
print(dict_demo.values())
Output : dict_values(['Hcl', 'WIPRO', 'TCS'])
45 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
QUESTIONS:
Winter-2022:
1. Describe Tuples in Python. (2M)
2. Write basis operations of list.(4M)
3. Write python program to perform following operations on Tuples.(6M)
i) Create set
ii) Access set Element
iii) Update set
iv) Delete set
4. Explain mutable and immutable data structures. (6M)
Summer-2022:
1. Explain four Buit-in tuple functions python with example. (4M)
2. Explain indexing and slicing in list with example. (4M)
3. Write a program to create dictionary of students that includes their ROLL NO. and
NAME. (4M)
i) Add three students in above dictionary
ii) Update name = ‘Shreyas’ of ROLL NO = 2
iii) Delete information of ROLL NO = 1
4. Write the output of the following : (6M)
i) >>> a = [ 2, 5, 1, 3, 6, 9, 7 ]
>>> a [ 2 : 6 ] = [ 2, 4, 9, 0 ]
46 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
Programs:
5. Write a Python program to sum all the items in a list.
6. Write a Python program to multiplies all the items in a list.
7. Write a Python program to get the largest number from a list.
8. Write a Python program to get the smallest number from a list.
9. Write a Python program to reverse a list.
10. Write a Python program to find common items from two lists.
11. Write a Python program to select the even items of a list.
12. Write a Python program to find the repeated items of a tuple.
13. Print the number in words for Example: 1234 => One Two Three Four.
14. Write a Python program to create a set, add member(s) in a set and remove one
item from set.
15. Write a Python program to perform following operations on set: intersection of
sets, union of sets, set difference, symmetric difference, clear a set.
16. Write a Python program to find maximum and the minimum value in a set.
17. Write a Python program to find the length of a set.
18. Write a Python script to sort (ascending and descending) a dictionary by value.
19. Write a Python script to concatenate following dictionaries to create a new one.
Sample Dictionary:
dic1 = {1:10, 2:20}
dic2 = {3:30, 4:40}
dic3 = {5:50,6:60}
20. Write a Python program to combine two dictionary adding values for common
47 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)
keys.
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
21. Write a Python program to print all unique values in a dictionary.
Sample Data: [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"},
{"VII":"S005"}, {"V":"S009"}, {"VIII":"S007"}]
22. Write a Python program to find the highest 3 values in a dictionary.
48 | P a g e
Prashant S. Bhandare