[go: up one dir, main page]

0% found this document useful (0 votes)
80 views48 pages

PWP Chapter 3

The document discusses Python data structures like lists, tuples, sets and dictionaries. It explains how to define, access and manipulate these structures. Common operations like indexing, slicing and built-in functions are also covered. Example programs are provided to demonstrate working with different data types in lists.

Uploaded by

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

PWP Chapter 3

The document discusses Python data structures like lists, tuples, sets and dictionaries. It explains how to define, access and manipulate these structures. Common operations like indexing, slicing and built-in functions are also covered. Example programs are provided to demonstrate working with different data types in lists.

Uploaded by

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

Unit 3: Data structures in Python Programming with “Python” (22616)

Name of Staff: Mr. P. S. Bhandare


Name of Subject: Programming with Python
Subject code: 22616
Class: TYCO
Department: Computer Engineering

Unit No. 3
Data Structures in Python
by
P. S. Bhandare

College of Engineering (Polytechnic),


Pandharpur

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)

About Title of Chapter:

 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.

About Central Idea of Chapter:

 The central idea of chapter is that by studying this chapter student


will learn different data structure available in python programming
language & operations on that.

About Importance of Chapter:

 This chapter is important because this will introduce basic


operations on data structures like list, tuple dictionary etc. which are
used to solve different real-life problems

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

A sequence is a datatype that represents a group of elements. The


purpose of any sequence is to store and process a group of elements. In
Python, strings, lists, tuples and dictionaries are very important sequence
datatypes. All sequences allow some common operations like indexing and
slicing.

Following are the sequence data types:


1. List
2. Tuple
3. Set
4. Dictionary

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:

10, 'Poly tech, м, 50, 55, 62, 74, 66

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:

elst = [ ] #this an empty list

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)

The list appears as given below:

[10, ‘Poly tech’, 'M', 50, 55, 62, 74, 66]

Indexing and slicing operations are commonly done on lists. Indexing


represents accessing elements by their position numbers in the list. The
position numbers start from O onwards and are written inside square
braces as: student[0], student[1], etc... It means, student[0] represents 0th
element, student[1] represents 1st element and so forth. For example, to
print the student's name, we can write:

print(student[1])

The name of student appears as given below:


Poly tech

Slicing represents extracting a piece of the list by mentioning starting and


ending position numbers. The general format of slicing is: [start: stop:
stepsize]. By default, 'start' will be 0, 'stop' will be the last element and
'stepsize' will be 1. For example, student [0:3:1] represents a piece of the
list containing 0th to 2nd elements.

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)

We can also write the above statement as:

print (student [:3:])

The same elements appear as shown following: [


10, ‘Poly tech’, 'M'

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.

A Python program to create lists with different types of elements.


# a general way to create lists
# create a list with integer numbers
num = [10, 20, 30, 40, 501
print('Total list=’,num)# display total list
print('First= %d, Last= %d % (num[0], num [4])) # display first and
last

# create a list with strings


names= ["Raju", "Vani", "Gopal", "Laxmi"]
print('Total list=', names) # display entire list
print('First= %s, Last= %s' % (names[0], names[3])) # display first and
last

create a list with different elements


x= [10, 20, 10.5, 2.55, "Ganesh", 'Vishnu']
print('Total list= ', x) # display entire list # elements

6|Page
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)

print('First=%d, Last= %s' % (x[0], x[5])) # display first and last


Creating Lists using range() Function

We can use range() function to generate a sequence of integers which can


be stored in a list. The format of the range() function is:
range(start, stop, stepsize)
If we do not mention the 'start', it is assumed to be O and the 'stepsize' is
taken as 1. The range of numbers stops one element prior to 'stop'. For
example,
range(0, 10, 1)

This will generate numbers from 0 to 9, as: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] .


Consider another
range (4, 9, 2)
The preceding statement will generate numbers from 4th to 8th in steps of
2, i.e. [4, 6, 8]

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)

The preceding statements will give the following output:


range (4, 9,2) # this is not a list,

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.

A Python program to create lists using range() function.


list1 = range(10)
for i in listl: # display element by element
print(i, end=’’)
print() # throw cursor to next line

#create list with integers from 5 to 9


list2 = range(5, 10)
for i in list2:
print(i, ', ', end='')
print()

# create a list with odd numbers from 5 to 9


list3 = range(5, 10, 2) # step size is 2
for i in list3:
print(i, ', ', end='')

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)

while i<len(list): # repeat from 0 to length of list


print(list[i])
i=i+1

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.

Another way to display elements of a list is by using a for loop, as:

for i in list: # repeat for all elements


print(i)

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.

Updating the Elements of a List

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.

lst = list(range(1,5)) # create a list using list() and range()


print(lst)

The preceding statements will give the following output:


[1, 2, 3, 4]
Now, consider the following statements:
lst.append(9)
# append a new element to lst
The preceding statements will give the following output:
[1, 2, 3, 4, 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]=8 # update 1st element of lst


print(lst)
The preceding statements will give:
[1, 8, 3, 4, 9]

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.

del lst [1]


print(1st) # delete 1st element from lst
Now, the list appears as:
[1, 11, 4, 9]

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)

example, let's assume a list with 5 elements. The positions of these


elements can be specified using indexing, as: list [0] to list [4] To display in
reverse order, we should follow the order: list [4] to list [0]. The following
while loop can be used to display the list in reverse order:

while i >= 0 #i represents initially 4.


print(list[i]) # display from 4th to Oth elements
i-=1
In the previous code, i starts with a value n-1' where ‘n' represents the
number of elements of the list. Thus, if the list has 5 elements, i would start
from 4th element onwards till Oth element.

Another way to access elements in reverse order is by using negative


indexing. When we write list [- 1], it represents the last element. List [- 2]
represents 2nd element from the end. Hence, we should display from list [-
1] to list [- 5] so that the list will be displayed in reverse order.

i = - 1 # last element
while i >= - 5 # display from -1th to -5th elements
print(days[i])
i -=1 #decrease the position every time.

Concatenation of Two Lists

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:

chi = [10, 20, 30, 40, 50]


a = 20 print(a in x) # check if a is member of x
The preceding statements will give: True
If you write,
print(a not in x) # check if a is not a member of x
Then, it will give: False

Aliasing and Cloning Lists


Giving a new name to an existing list is called 'aliasing'. The new name is
called 'alias name'. For example, take a list 'x' with 5 elements as
X = [10, 20, 30, 40, 50]
To provide a new name to this list, we can simply use assignment operator
as:
y=x
In this case, we are having only one list of elements but with two different
names ‘x' and ‘y'. Here, ‘x' is the original name and ‘y' is the alias name for
the same list. Hence, any modifications done to ‘x' will also modify ‘y' and
vice versa. Observe the following statements where an element x[1] is
modified with a new value.
X = [10, 20, 30, 40, 50]
y = x #x is aliased as y
print(x) #will display[10, 20, 30, 40, 50]
x[1]=99
print(x) #will display[10, 99, 30, 40, 50]
print(y) #will display[10, 99, 30, 40, 50]

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]

We can observe that in cloning, modifications to a list are confined only to


that list. The same can be achieved by copying the elements of one list to
another using copy() method. For example, consider the following
statement:

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)

print("The list after axtend() operator is: ",my_list)


Output:

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:

We can see that element 10 is removed from the list.


5. Pop()
There is an inbuilt function to remove the last element from the list known as pop().
my_list.pop()
print("The list after pop() operator is:\n",my_list)

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))

The length, maximum and minimum element in my_list are:

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:

Here 2 shows the number of occurrences of element 23.


10. Concatenate
Concatenate is a very simple process, with the literal meaning of combining or joining
two objects. Similarly, concatenation in Python can be used to combine two lists or
strings. Concatenation in Python can be simply performed by using “+” between
variable names that hold a string or list.
Example:
list_one = [100, 150, 200]
list_two = [900, 950, 800]
new_list = list_one + list_two #new_list variable holds the concatenated list
print(new_list)
Output:

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

append() Adds an element to the end of the list

extend() Adds more than one element to the end of the list

insert() Adds an element in between the list

remove() Removes an elements from the list

pop() Removes the last elements from the list

slice() Prints a section of the list

reverse() Reverses the order of the elements in a list

len() Gives the length of a list

min() Gives the minimum element (by value) of a list

max() Gives the maximum element (by value) of a list

count() Counts the number of copies in a list

Concatenate Combines two list

Multiply Multiplies the occurrence of elements in a list

index() Gives index number of an element in the list

sort() Sorts the list in ascending order

clear() Clears every element in a list

Sum() Return sum of all the elements

17 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)

Finding the greater and smaller in list:


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)
big=x[0]
small=x[0]
for i in range(1,n):
if x[i]>big:
big=x[i]
if x[i]<small:
small=x[i]
print("Big= ",big)
print("Small= ",small)
"""
o/p:
Enter how many element: 7
Enter element to add to list: 22
Enter element to add to list: 11
Enter element to add to list: 33
Enter element to add to list: 55
Enter element to add to list: 44
Enter element to add to list: 77
Enter element to add to list: 66
List= [22, 11, 33, 55, 44, 77, 66]
Big= 77
Small= 11
"""
Number of occurrences of element in list:

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
"""

Finding Common Elements in Two Lists:


L1= [22, 11, 33, 55, 44, 77, 66]
L2=[22, 88, 99, 110, 44, 77, 66]
s1=set(L1)
s2=set(L2)
s3=s1.intersection(s2)
common=list(s3)
print("Common= ",common)

"""
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)

The tuple is shown as: (1, 2, 3)


Another way to create a tuple is by using range() function that returns a
sequence. To create a tuple tpl' that contains numbers from 4 to 8 in steps of 2,
we can use the range) function along with tuple() function, as:
Tp1= tuple(range(4, 9, 2)) # numbers from 4 to 8 in steps of 2
print(tpl)
The preceding statements will give: (4, 6, 8)

Accessing the Tuple Elements


Accessing the elements from a tuple can be done using indexing or slicing. This is
same as that of a list. For example, let's take a tuple by the name tup' as:
tup=( 50, 60, 70, 80 ,90,100)
Indexing represents the position number of the element in the tuple. Now, tup[0]
represents the 0th element, tup[1] represents the 1st element and so on.
print(tup[0])
The preceding will give: 50
Now, if you write:
print(tup [5])
Then the following element appears: 100
Similarly, negative indexing is also possible. For example, tup[- 1] indicates the
last element and tup[- 2] indicates the second element from the end so on.
Consider the following statement:

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)

print(tup[::2]) #here, start and stop assume default values.


The following output appears: (50, 70, 90)
Negative values can be given in the slicing. If the 'step size' is negative, the
elements are extracted in reverse order as:
print(tup[::-2])
The elements appear in the reverse order: (100, 80, 60)
When the step size is not negative, the elements are extracted from left to right.
In the following example, starting position -4 indicates the 4th element from the
last. Ending position-1 indicates the last element. Hence, the elements from 4th
to one element before the ending element (left to right) will be extracted.
print(tup[-4:-1]) #here, step size is 1
The following elements appear: (70, 80, 90)
In most of the cases, the extracted elements from the tuple should be stored in
separate variables for further use. In the following example, we are extracting the
first two elements from the 'student' tuple and storing them into two variables.
student =(10, 'vinay kumar', 50,60,65,61,70)
rno,name=student[0:2]
Now, the variable 'rno' represents 10 and 'name' represents Vinay kumar.
Consider the following statement:
print(rno)
The preceding statement will give: 10
Now, if you write: print(name)
The preceding statement will provide the name of the student: Vinay kumar
If we want to retrieve the marks of the student from 'student' tuple, we can do it
as:
marks =student [2:7] # store the elements from 2 to 6th into 'marks'
for i in marks:
print(i)
The preceding statements will give the following output:
50
60
65
61
70

Basic Operations on Tuples


The 5 basic operations: finding length, concatenation, repetition, membership
and iteration operations can be performed on any sequence maybe it is a string,
list, tuple or a dictionary.
To find length of a tuple, we can use len() function. This returns the number of
elements in the tuple.
Consider the following example:

22 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)

Student =( 10 , 'Vinaykumar', 50,60,65,61,70)


Len(student)
The preceding statement will give the following output: 7
We can concatenate or join two tuples and store the result in a new tuple. For
example, the student paid a fees of Rs. 25,000.00 every year for 4 terms, then we
can create a fees' tuple as:
fees=( 25000 ,) * 4 # repeat the tuple elements for 4 times.
print (fees)
The preceding statement will give the following output: (25000.0, 25000.0,
25000.0, 25000.0)
Now, we can concatenate the 'student' and 'fees' tuples together to form a
new tuple 'student1' as:
student1 = student+fees
print(student1)
The preceding statement will give:
(10, 'Vinay kumar', 50, 60, 65, 61, 70, 25000.0, 25000.0, 25000.0, 25000.0)
Searching whether an element is a member of the tuple or not can be done
using in' and 'not in' operators. The in' operator returns True if the element is a
member. The not in' operator returns True if the element is not a member.
Consider the following statements:
name='Vinay kumar' # to know if this is member of student1 or not
name in student1
The preceding statements will give: True
Suppose if you write:
name not in studentl
Then the following output will appear: False
The repetition operator repeats the tuple elements. For example, we take a tuple
tpl' and repeat its elements for 4 times as:
tp1 = (10, 11, 12)
tp1 = tp1 * 3
print( tp1) # repeat for 3 times and store in tpl1
The preceding statements will give the following output:
(10, 11, 12, 10, 11, 12, 10, 11, 12)
1. Concatenation operator (+):
The (+) operator is used to add to two tuples.
The syntax of the given operation is: Tuple1+Tuple2
t1=(12, 34, 56)
t2=(78, 90)
print(t1+t2)
Output : (12, 34, 56, 78, 90)

23 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)

2. Repetition operator (*)


Like string and list, (*) operator replicates the element of the tuple of specified
times. The syntax of the given operation: Tuple*n
t1=(12, 34, 56)
print( t1*3)#Output
(12, 34, 56, 12, 34, 56, 12, 34, 56)
3. Comparison Operator:
Python offers standard comparison operators like ==,<, >, != to compare two lists.
For comparison, two tuples must-have elements of comparable types, otherwise,
you will get an error.
Python gives the result of comparison operators as True or False and moreover, it
compares tuple list element by element. It compares the first element if they are
the same then will move to the next, and so on.
5. Membership Operator (in, not in)
The membership operator checks whether an element exists in the given tuple
sequence.
in: Return True if an element exists in the given tuple; False otherwise
not in: Return True if an element does not exist in the given tuple; False
otherwise.
t1=(12, 34, 56, 78, 90)
#membership operator
56 in t1
12 not in t1
Output:
True
False

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')

Deleting Element from Tuple:


The first one is that a tuple by definition is not able to be changed it is immutable.
And so the different techniques that we're going to use to remove elements
they're not going to actually be removing elements from the original tuple those
created much in the same manner as when we added elements to the tuple.

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)

o/p: Enter Position: 3


(11, 22, 44, 55, 66, 77, 88, 99)

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))

Adding items to the set:

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)

2. Using update() method:


Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nupdating the original set ... ")
Months.update(["July","August","September","October"]);
print("\nprinting the modified set ... ")
print(Months);

28 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)

Removing items from the set:

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)

print("\nPrinting the modified set...");


print(Months)
4. Using clear() method:
Python provides the clear() method to remove all the items from the set.
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving all the items from the set...");
Months.clear()
print("\nPrinting the modified set...")
print(Months)

Python Set Operations :


1. Union of two Sets:
To combine two or more sets into one set in Python, use the union() function. All
of the distinctive characteristics from each combined set are present in the final
set. As parameters, one or more sets may be passed to the union() function. 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 containing all the different items from all
the arguments if more than one set is supplied as an argument.

using union | operator:


Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1|Days2) #printing the union of the sets

using union() method


Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1.union(Days2)) #printing the union of the sets

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.

Using & operator


Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday","Tuesday","Sunday", "Friday"}
print(Days1&Days2) #prints the intersection of the two sets

Output:
{'Monday', 'Tuesday'}

Using intersection() method

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

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.

a = {"Devansh", "bob", "castle"}


b = {"castle", "dude", "emyway"}
c = {"fuson", "gaurav", "castle"}
a.intersection_update(b, c)
print(a)

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)

Example 1 : Using subtraction ( - ) operator

Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}


Days2 = {"Monday", "Tuesday", "Sunday"}
print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}
Output:
{'Thursday', 'Wednesday'}
Example 2 : Using difference() method

Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}


Days2 = {"Monday", "Tuesday", "Sunday"}
print(Days1.difference(Days2)) # prints the difference of the two sets Days1 a
nd Days2
Symmetric Difference of two sets

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.

The Symmetric Difference of two sets can be computed using Python's


symmetric_difference() method. This method returns a new set containing all the
elements in either but not in both.

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.

Here are the set comparison operators available in Python:

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).

Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}


Days2 = {"Monday", "Tuesday"}
Days3 = {"Monday", "Tuesday", "Friday"}

34 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)

#Days1 is the superset of Days2 hence it will print true.


print (Days1>Days2)
#prints false since Days1 is not the subset of Days2
print (Days1<Days2)
#prints false since Days2 and Days3 are not equivalent
print (Days2 == Days3)

Python Built-in set methods

SN Method Description

1 add(item) It adds an item to the set. It has no effect if the item is


already present in the set.

2 clear() It deletes all the items from the set.

3 copy() It returns a shallow copy of the set.

4 difference_update(....) It modifies this set by removing all the items that are
also present in the specified sets.

5 discard(item) It removes the specified item from the set.

6 intersection() It returns a new set that contains only the common


elements of both the sets. (all the sets if more than two
are specified).

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).

8 Isdisjoint(....) Return True if two sets have a null intersection.

9 Issubset(....) Report whether another set contains this set.

10 Issuperset(....) Report whether this set contains another set.

11 pop() Remove and return an arbitrary set element that is the


last element of the set. Raises KeyError if the set is
empty.

12 remove(item) Remove an element from a set; it must be a member. If


the element is not a member, raise a KeyError.

35 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)

13 symmetric_difference(....) Remove an element from a set; it must be a member. If


the element is not a member, raise a KeyError.

14 symmetric_difference_update(....) Update a set with the symmetric difference of itself and


another.

15 union(....) Return the union of sets as a new set.


(i.e. all elements that are in either set.)

16 update() Update a set with the union of itself and others.

Python Dictionary

A dictionary represents a group of elements arranged in the form of key-value


pairs. In the dictionary, the first element is considered as 'key' and the
immediate next element is taken as its 'value'. The key and its value are
separated by a colon (:). All the key-value pairs in a dictionary are inserted in
curly braces {). Let's take a dictionary by the name 'dict' that contains
employee details:

dict = {'Name': 'Poly', 'Id': 200, 'Salary': 9080.50]

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.

 The data is stored as key-value pairs using a Python dictionary.


 This data structure is mutable
 The components of dictionary were made using keys and values.
 Keys must only have one component.
 Values can be of any type, including integer, list, and tuple.

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.

Creating the Dictionary

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 an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)

# 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)

Accessing the dictionary values


To access data contained in lists and tuples, indexing has been studied. The
keys of the dictionary can be used to obtain the values because they are
unique from one another. The following method can be used to access
dictionary values.

Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}


print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])

using get() method:

car={ "brand": "Ford", "model": "Mustang", "year": 1964}


x=car.get("model")
print(x)

Adding Dictionary Values:

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.

# Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)

38 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)

# Adding elements to dictionary one at a time


Dict[0] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# with a single Key
# The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Updating existing Key's Value


Dict[3] = 'JavaTpoint'
print("\nUpdated key value: ")
print(Dict)

Program-2:

Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}


print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Enter the details of the new employee....");
Employee["Name"] = input("Name: ");
Employee["Age"] = int(input("Age: "));
Employee["salary"] = int(input("Salary: "));
Employee["Company"] = input("Company:");
print("printing the new data");
print(Employee)

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)

Deleting Elements using pop() Method


A dictionary is a group of key-value pairs in Python. You can retrieve, insert,
and remove items using this unordered, mutable data type by using their
keys. The pop() method is one of the ways to get rid of elements from a
dictionary. The value connected to a specific key in a dictionary is removed
using the pop() method, which then returns the value. The key of the element
to be removed is the only argument needed.

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

# for loop to print all the keys of a dictionary


Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in Employee:
print(x)

40 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)

#for loop to print all the values of the dictionary


Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in Employee:
print(Employee[x])

#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

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

41 | P a g e
Prashant S. Bhandare
Unit 3: Data structures in Python Programming with “Python” (22616)

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist: insert the key,
with the specified value

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary

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.

dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}


len(dict)

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.

dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}


any({'':'','':'','3':''})

Output : True

o all()

Unlike in any() method, all() only returns True if each of the dictionary's keys
contain a True Boolean value.

dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}


all({1:'',2:'','':''})

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.

dict = {7: "Ayan", 5: "Bunny", 8: "Ram", 1: "Bheem"}


sorted(dict)

Output : [ 1, 5, 7, 8]

Built-in Dictionary methods

The built-in python dictionary methods along with the description and Code are
given below.

o clear()

It is mainly used to delete all the items of the dictionary.

# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# clear() method
dict.clear()
print(dict)
Output: { }

o copy()

It returns a shallow copy of the dictionary which is created.

# 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)

Output: {1: 'Hcl', 2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}

o pop()

It mainly eliminates the element using the defined key.

# 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()

removes the most recent key-value pair entered

# 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()

It returns all the keys of the dictionary.

# 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()

It returns all the key-value pairs as a tuple.

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)

>>> print (a)


ii) >>> b = [ “Hello” , “Good” ]
>>> b. append ( “python” )
>>> print (b)
iii) >>> t1 = [ 3, 5, 6, 7 ]
>>> print ( t1 [2] )
>>> print ( t1 [–1] )
>>> print ( t1 [2 :] )
>>> print ( t1 [ : ] )

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

You might also like