202044504 - Programming with Python
UNIT – 2 – PART - 2
Python Data Structures
&
Functions
By:
Pratik B. Soni
Asst. Prof.
IT Dept.,
MBIT
1
Pratik B. Soni CVMU
OUTLINE
• Strings & its Methods
• Python Data-structures
• List
• Set
• Python Functions
• Types
• Arguments
• Recursive functions
• Local & Global Variables
• Anonymous Functions
2
Pratik B. Soni
Tuples
3
Pratik B. Soni
Tuple - Introduction
• But Lists & dictionaries are Mutable.
• Tuples, String & integers are immutable.
Mutable Immutable
Data type whose values can be changed Data types whose values can’t be
Definition
after creation. changed or altered.
Memory Retains the same memory location even Any modification results in a new object
Location after the content is modified. and new memory location
Example List, Dictionaries, Set Strings, Types, Integer
It is memory-efficient, as no new
It might be faster in some scenarios as
Performance objects are created for frequent
there’s no need to track changes.
changes.
Not inherently thread-safe. Concurrent
They are inherently thread-safe due to
Thread-Safety modification can lead to unpredictable
their unchangeable nature.
results.
When you need to modify, add, or When you want to ensure data remains
Use-cases
remove existing data frequently. consistent and unaltered.
4
Pratik B. Soni
Tuple - Introduction
• Tuple can use ( ) for their elements / items
• E.g.)
empty tuple
with one element (must need comma at end)
5
Pratik B. Soni
Tuple - Introduction
list1 = [1,2,3]
tuple1 = tuple(list1)
print(tuple1)
output :
(1,2,3)
tuple1 = tuple(range(4,9,2))
print(tuple1)
output :
(4,6,8)
6
Pratik B. Soni
Tuple - Introduction
• Accessing Tuple Elements
tuple1 = (50,60,70,80,90,100)
print(tuple1[0]) - output: 50
print(tuple1[5]) - output: 100
print(tuple1[-1]) - output: 100
print(tuple1[-6]) - OUTPUT: 50
7
Pratik B. Soni
Tuple - Introduction
• Accessing Tuple Elements
tuple1 = (50,60,70,80,90,100)
print(tuple1[:]) - output: (50,60,70,80,90,100)
print(tuple1[1:4]) - output: (60,70,80)
print(tuple1[::2]) - output: (50,70,90)
print(tuple1[::-2]) - OUTPUT: (100,80,60)
print(tuple1[::-2]) - OUTPUT: (100,80,60)
8
Pratik B. Soni
Tuple - Introduction
• accessing tuple elements with variables
tuple1 = (10,’xyz’,50,60,70,80)
roll,name = tuple1(0:2)
print(roll) - output: 10
print(name) - output: xyz
marks = tuple1(2:6)
for i in marks:
print(marks)
output: (50,60,70,80)
9
Pratik B. Soni
Tuple – Basic Operations
• Length of Tuple – len() function
student = (10,’xyz’,50,60,70,80)
len(student)
output: 6
• Repeat Tuple elements (‘*’)
fees = (25000.0,)*4
print(fees)
output:
(25000.0, 25000.0, 25000.0, 25000.0)
• CONCAT two Tuples (‘+’)
student1 = student + fees
output:
(10,’xyz’,50,60,70,80, 25000.0, 25000.0, 25000.0, 25000.0)
10
Pratik B. Soni
Tuple – Basic Operations
• Member of List / Not (‘in’ and ‘not in’)
student = (10,’xyz’,50,60,70,80)
name = ‘xyz’
name in student
output:
True
student = (10,’xyz’,50,60,70,80)
id = 11
id not in student
output:
True
11
Pratik B. Soni
Tuple – Take Value from User as a tuple
• eval() – function , to take value from user.
e.g.)
tuple1 = eval(input(“enter tuple elements in ():”))
for i in range(len(tuple)):
print(tuple[i])
output:
enter tuple elements in (): (1,2,3,4,5,6)
1
2
3
4
5
6
12
Pratik B. Soni
Tuple – Basic Functions
FUNCTION EXAMPLE Description
len() len(tuple) returns number of elements in
tuple
min() min(tuple) returns smallest element in
tuple
max() max(tuple) returns biggest element in tuple
count() [Link](x) return how many times the
element ‘x’ in tuple
index() [Link](x) returns the first occurrence of
element in tuple
sorted() sorted(tuple) sorts the tuple into ascending,
sorted(reverse=true) for
descending order
13
Pratik B. Soni
Tuple – Take Value from User as a tuple
• eval() – function , to take value from user.
e.g.)
sum =0
tuple1 = eval(input(“enter tuple elements in ():”))
for i in range(len(tuple)):
sum=sum+tuple[i]
print(“sum is:”,sum)
output:
enter tuple elements in (): (1,2,3,4,5,6)
Sum is: 21
14
Pratik B. Soni
Tuple – Take Value from User as a tuple
• index() – function , to find first occurrence element in tuple.
e.g.)
tuple1 = eval(input(“enter tuple elements in ():”))
num = int(input(“enter no:”))
pos = tuple1index(num)
print(“pos is:”,pos)
output:
enter tuple elements in (): (1,2,3,4,5,6)
enter no: 2
pos is: 1
15
Pratik B. Soni
Tuple – Nested
• e.g.)
t1 = (1,2,3,4, (5,6))
• t1 is tuple with nesting with 5 elements
print(t1[5])
output: (5,6)
16
Pratik B. Soni
Tuple – Take Value from User as a tuple
• index(<>) – function , to find first occurrence element in tuple.
e.g.)
tuple1 = eval(input(“enter tuple elements in ():”))
num = int(input(“enter no:”))
pos = [Link](num)
print(“pos is:”,pos)
output:
enter tuple elements in (): (1,2,3,4,5,6)
enter no: 2
pos is: 1
17
Pratik B. Soni
Tuple – Insert Element
• Tuples are immutable.
• We cannot modify elements of tuple once it is created.
• Lists are Mutable.
• We can modify elements in any list.
18
Pratik B. Soni
Tuple – Insert Element
• Tuples are immutable.
• We cannot modify elements of tuple once it is created.
• So, we can do following steps for Insert element in tuple
• Take tuple part before enter element index (copy)
• Add that element at last position (concat)
• Add rest of tuple part at last and store in new tuple (concat)
19
Pratik B. Soni
Tuple – Insert Element
x = (10,20,30,40,50,60)
pos = 2 (position at which element to be add)
new = new element to be entered = (<int>,)
y = x[0:pos]
y = y + new
x = y+ x[pos:]
20
Pratik B. Soni
Tuple – Modify Element
• Steps:
• Take tuple upto modify position into another tuple
• Concat new element
• Add remaining positions after modified position
x = (10,20,30,40,50,60)
pos = 2 (position at which element to be add)
new = new element to be entered = (int,)
y = x[0:pos]
y = y + new
x = y+ x[pos+1:]
21
Pratik B. Soni
Tuple – Delete Element
• Steps:
• Take tuple upto modify position into another tuple
• Add remaining positions after the position which need to remove
x = (10,20,30,40,50,60)
pos = 2 (position at which element to be delete)
y = x[0:pos]
x = y+ x[pos+1:]
22
Pratik B. Soni
SET
23
Pratik B. Soni
SET - Introduction
• Sets are used to store multiple items in a single variable.
• A set is a collection which is unordered, unchangeable*, and
unindexed.
• Sets are written with curly brackets.
• E.g.)
thisset = {"apple", "banana", "cherry"}
print(thisset)
24
Pratik B. Soni
SET - Items
• Set items are unordered, unchangeable, and do not allow duplicate
values.
Unordered
• Unordered means that the items in a set do not have a defined
order.
• Set items can appear in a different order every time you use
them, and cannot be referred to by index or key.
Unchangeable
• Set items are unchangeable, meaning that we cannot change
the items after the set has been created.
• Once a set is created, you cannot change its items, but you can
remove items and add new items.
Duplicates Not Allowed
• Sets cannot have two items with the same value.
25
Pratik B. Soni
SET – Items –
Unordered, Boolean, Length
26
Pratik B. Soni
SET – Items – Data Types
27
Pratik B. Soni
SET – Constructor
SET Example
SET Constructor – two round Brackets
28
Pratik B. Soni
SET – Access Set Items
• Access items in a set by referring to an index or a key.
29
Pratik B. Soni
SET – ADD Set Items
• Set is Unchangeable.
• So, Change of any item is not possible but adding is possible.
add() Function - Add an item to a set
update() Function - Add items to set
30
Pratik B. Soni
SET – ADD Set Items
update() Function
• It can be any iterable object (tuples, lists, dictionaries etc.).
31
Pratik B. Soni
SET – Remove Set Items
remove() Function –
If the item to remove does not exist, remove() will raise an error.
discard() Function –
If the item to discard does not exist, remove() will NOT raise an error.
32
Pratik B. Soni
SET – Remove Set Items
pop() Function –
It removes random item (any one)
33
Pratik B. Soni
SET – Remove Set Items
clear() Function –
It removes all set items – Empty set
del keyword –
It deletes the set.
34
Pratik B. Soni
SET – Loop Sets
35
Pratik B. Soni
SET – JOIN Sets
There are several ways to join two or more sets in Python.
• The union() and update() methods joins all items from both
sets.
• The intersection() method keeps ONLY the duplicates.
• The difference() method keeps the items from the first set that
are not in the other set(s).
• The symmetric_difference() method keeps all items EXCEPT
the duplicates.
36
Pratik B. Soni
SET – JOIN Sets
• The union() method joins all items from both sets.
• Using union() function and “|” operator
37
Pratik B. Soni
SET – JOIN Sets
• The union() method joins all items from both sets.
• JOIN MULTIPLE SETS – using union()
38
Pratik B. Soni
SET – JOIN Sets
• The union() method joins all items from both sets.
• JOIN MULTIPLE SETS – using “|” operator
39
Pratik B. Soni
SET – JOIN Sets
• The update() method joins all items from both sets.
• method inserts the items from one set to another set
Both union() and update() will exclude
any duplicate items.
40
Pratik B. Soni
SET – JOIN Sets
• The intersection() method – “&” operator
• Returns new set with same items of two sets.
The & operator only allows to join sets with sets, and not with
other data types like you can with the intersection() method.
41
Pratik B. Soni
SET – JOIN Sets
• The intersection() method – “&” operator
• Returns new set with same items of two sets.
42
Pratik B. Soni
SET – JOIN Sets
• The intersection_update() method
• Keep ONLY the duplicates, but it will change the original set instead of
returning a new set.
43
Pratik B. Soni
SET – JOIN Sets
• The difference() method and “-” operator
• Returns return a new set that will contain only the items from the first set
that are not present in the other set.
The “–” operator only allows you to join sets
with sets, and not with other data types like
you can with the difference() method.
44
Pratik B. Soni
SET – JOIN Sets
• The difference_update() method and “-” operator
• Returns return a set with difference but change the original set
45
Pratik B. Soni
SET – JOIN Sets
• The symmetric_difference() method and “^” operator
• keep only the elements that are NOT present in both sets.
The “^” operator only allows you to join sets
with sets, and not with other data types like you
can with the symmetric_difference() method.
46
Pratik B. Soni
SET – JOIN Sets
• symmetric_difference_update() – it changes the original set
47
Pratik B. Soni
SET – Methods
Method Shortcut Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() - Returns a set containing the difference between two
or more sets
difference_update() -= Removes the items in this set that are also included in
another, specified set
discard() Remove the specified item
intersection() & Returns a set, that is the intersection of two other sets
intersection_update() &= Removes the items in this set that are not present in
other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
48
Pratik B. Soni
SET – Methods
Method Shortcut Description
issubset() <= Returns whether another set contains this set or not
< Returns whether all items in this set is present in other,
specified set(s)
issuperset() >= Returns whether this set contains another set or not
> Returns whether all items in other, specified set(s) is present in
this set
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() ^ Returns a set with the symmetric differences of two sets
symmetric_difference_u ^= Inserts the symmetric differences from this set and another
pdate()
union() | Return a set containing the union of sets
update() |= Update the set with the union of this set and others
49
Pratik B. Soni
Dictionary
50
Pratik B. Soni
Dictionary - Introduction
• Python provides another composite data type called
a dictionary, which is similar to a list in that it is a collection of
objects.
• Dictionaries are used to store data values in pairs.
• E.g.)
d = { <key>: <value>,
<key>: <value>,
...
<key>: <value> }
51
Pratik B. Soni
Dictionary - Introduction
52
Pratik B. Soni
Dictionary - Introduction
• Dictionaries are ordered,
• It means that the items have a defined order, and that
order will not change.
• Dictionaries are changeable,
• meaning that we can change, add or remove items after
the dictionary has been created.
• Dictionary does not have duplicate keys.
• Duplicate values will overwrite existing values - LATEST
53
Pratik B. Soni
Dictionary vs List
• Dictionaries and lists share the following characteristics:
Both are mutable.
Both are dynamic. They can grow and shrink as needed.
Both can be nested. A list can contain another list. A dictionary
can contain another dictionary. A dictionary can also contain a
list, and vice versa.
• Dictionaries differ from lists primarily in how elements are
accessed:
List elements are accessed by their position in the list, via
indexing.
Dictionary elements are accessed via keys.
54
Pratik B. Soni
Dictionary – len() function
• Gives no. of keys available (duplicate keys considered
as one key)
55
Pratik B. Soni
Dictionary – TYPE
• Dictionary items are of any Type.
• type(dictionary_name) prints Dictionary as an o/p.
56
Pratik B. Soni
Dictionary – use of dict() constructor
• dict() constructor is used to initialized dictionary.
• E.g.)
57
Pratik B. Soni
Dictionary – basic operations - access
• Accessing dictionary items – 2 ways
• As argument
• Using get(‘<<key>>’)
• E.g.)
58
Pratik B. Soni
Dictionary – basic operations - access
• Get keys of dictionary – keys()
• E.g.)
59
Pratik B. Soni
Dictionary – basic operations - access
• ADD new item to dictionary
1) Get keys()
2) Add item to dictionary
• E.g.)
60
Pratik B. Soni
Dictionary – basic operations - access
• Get values of dictionary – values()
• E.g.)
61
Pratik B. Soni
Dictionary – basic operations - access
• Change any value to dictionary
1) Get values
2) Change the value
• E.g.)
62
Pratik B. Soni
Dictionary – basic operations - access
• Get items in tuple format – items()
• E.g.)
63
Pratik B. Soni
Dictionary – basic operations - access
• Check if key exists or not – in / not in
• E.g.)
64
Pratik B. Soni
Dictionary – basic operations - access
• Check if key exists or not – in / not in
• E.g.)
65
Pratik B. Soni
Dictionary – basic operations - Change
• Using syntax
• Using update()
• E.g.)
66
Pratik B. Soni
Dictionary – basic operations - ADD
• Using syntax
• Using update()
• E.g.)
67
Pratik B. Soni
Dictionary – basic operations - REMOVE
• Using pop() – remove specified as function argument
• Using popitem() – remove last item from dictionary
• E.g.)
68
Pratik B. Soni
Dictionary – basic operations - REMOVE
• Using del(<<key>>) – remove specified key
• Using del(<<dict>>) – remove/delete dictionary
• E.g.)
69
Pratik B. Soni
Dictionary – basic operations - REMOVE
• Using clear() – to empty the dictionary
• E.g.)
70
Pratik B. Soni
Dictionary – basic operations – Loop
• Print dictionary in loops
• E.g.)
71
Pratik B. Soni
Dictionary – basic operations – copy()
• copy a dictionary
• Using copy() method
• Without copy() method
• E.g.)
72
Pratik B. Soni
Dictionary – basic operations – Nested
• A dictionary can contain dictionaries, this is called nested
dictionaries.
E.g.)
73
Pratik B. Soni
Dictionary – basic operations – Nested
• A dictionary can contain dictionaries, this is called nested
dictionaries.
E.g.)
74
Pratik B. Soni
Dictionary – basic operations – Nested
• Access NESTED Dictionary items
• E.g.)
75
Pratik B. Soni
Dictionary – Functions
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
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
76
Pratik B. Soni
Dictionary – Convert List to Dictionary
77
Pratik B. Soni
Dictionary – Convert List to Dictionary
78
Pratik B. Soni
Dictionary – Convert String to Dictionary
1) eval(<string>)
2) “ast” library import
• ast.literal_eval(<string>)
3) “json” library import
• [Link](<string>)
79
Pratik B. Soni
Dictionary – pass as an Argument in function
80
Pratik B. Soni