PYTHON FOR ENGINEERS
OEEC6205
4th Semester, B. Tech(CSE)
IGIT, Sarang
SYLLABUS
Module III
Tuples: Creating Tuples, Basic Tuple Operations,
Indexing and Slicing in Tuples, Built-In Functions used
on Tuples, Tuple Methods, Using zip() Function,
Relation between Tuples and Lists.
Dictionaries: Creating Dictionary, Accessing and
Modifying key:value Pairs in Dictionaries, Built-In
Functions used on Dictionaries, Dictionary Methods,
The del Statement, Relation between Tuples and
Dictionaries.
Sets: Creating Sets, Set Methods, Traversing of Sets,
Frozen set.
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
2
CSEA, IGIT, Sarang
TUPLES
A tuple is an immutable list of values.
It is created with the comma operator( , ), parentheses(( ))
and built-in function tuple( ).
Syntax-1(USING COMMA OPERATOR):
variable = element-1, [element-2, element-3, ..............]
Syntax-2(USING PARENTHESES):
variable = (element-1, [element-2, element-3, ..............])
Syntax-3(USING tuple( ) FUNCTION):
variable = tuple(string_literal/string_variable/tuple_variable)
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
3
CSEA, IGIT, Sarang
COMMA OPERATOR AND PARENTHESES
EXAMPLES
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
4
CSEA, IGIT, Sarang
tuple( ) FUNCTION EXAMPLES
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
5
CSEA, IGIT, Sarang
tuple( ) FUNCTION EXAMPLES
Tuples are immutable, that is, one cannot add or modify items once
the tuple is initialized.
Tuples don't have append( ) and extend( ) methods.
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
6
CSEA, IGIT, Sarang
CONCATENATION OPERATOR ( + )
More than one tuples can be appended using
concatenation operator (+).
Syntax:
Variable = Tuple_Variable1 + Tuple_Variable2 + ….
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
7
CSEA, IGIT, Sarang
PACKING AND UNPACKING TUPLES
Assignment of values in a tuple is called as packing
because it packs values together in a tuple.
So, the statement t = 1, 2, 3 [OR] t = (1, 2, 3) is called
packing.
Unpacking of individual element from tuples is done
using index method since the tuple elements are
indexed and starts with 0th index.
Unpacking of elements from a tuple can also be done
using multiple assignments.
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
8
CSEA, IGIT, Sarang
UNPACKING TUPLES EXAMPLES
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
9
CSEA, IGIT, Sarang
UNPACKING TUPLES EXAMPLES
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
CSEA,bapuji rao 10
IGIT, Sarang
TUPLE
FUNCTIONS
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
11
CSEA, IGIT, Sarang
len( ) FUNCTION
It returns the length of the tuple.
Syntax:
variable = len(tuple_name / (ele1, ele2, ......))
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
12
CSEA, IGIT, Sarang
max( ), min( ) FUNCTIONS
It returns the maximum and minimum value from
the tuple.
Syntax of max( ):
variable = max(tuple_name / (ele1, ele2, ......))
Syntax of min( ):
variable = min(tuple_name / (ele1, ele2, ......))
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
13
CSEA, IGIT, Sarang
reversed( ) FUNCTION
It reverses a tuple.
Syntax:
Variable_Name = reversed(tuple_name / (ele1, ele2, ......))
Variable = tuple(Variable_Name)
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
14
CSEA, IGIT, Sarang
sum( ) FUNCTION
It returns the sum of the elements of the tuple.
Syntax:
Variable = sum(tuple_name / (ele1, ele2, ......))
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
15
CSEA, IGIT, Sarang
all( ) FUNCTION
It returns true if all the elements of the tuple is true.
If the tuple is empty then it returns true.
Syntax:
variable = all(tuple_name / (ele1, ele2, ......))
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
16
CSEA, IGIT, Sarang
any( ) FUNCTION
It returns true if any element of the tuple is true.
If the tuple is empty then it returns false.
Syntax:
variable = any(tuple_name / (ele1, ele2, ......))
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
17
CSEA, IGIT, Sarang
sorted( ) FUNCTION
It sorts a tuple and returns the sorted list.
The tuple( ) function changes the sorted tuple object to a tuple
kind.
SYNTAX:
Variable = sorted(tuple_name/(ele1, ele2,....), [reverse=False])
Tuple_Variable = tuple(Variable)
o reverse = False (Optional): If it is not included then sorting is
in ascending order.
o reverse = True: If it is included then the sorting is in
descending order.
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
18
CSEA, IGIT, Sarang
EXAMPLES
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
19
CSEA, IGIT, Sarang
TUPLE
METHODS
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
20
CSEA, IGIT, Sarang
count( ) METHOD
It counts the given element in the tuple.
Syntax:
variable = (ele1, ele2, ....)/tuple_name.count(element)
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
21
CSEA, IGIT, Sarang
index( ) METHOD
The method returns the first occurrence of the given element
in the tuple.
This method raises a ValueError if the element is not found in
the tuple.
SYNTAX:
variable = tuple_name.index(element, start, end)
start (Optional): The starting index from where the search
starts.
end (Optional): The ending index till where the search
continues.
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
22
CSEA, IGIT, Sarang
EXAMPLES
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
23
CSEA, IGIT, Sarang
TUPLE INDEXING
Elements of tuples are accessed in indexing way.
The tuple elements indexing are numbered from 0
onwards.
SYNTAX:
tuple_name[index]
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
24
CSEA, IGIT, Sarang
EXAMPLE
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
25
CSEA, IGIT, Sarang
zip( ) FUNCTION
It is used for iterating more than two lists simultaneously
within list comprehension.
It passes arbitrary number of lists.
It returns iterable zip object.
The zip object can be changed to either list / tuple kind using
functions list( ) / tuple( ).
SYNTAX:
zip(list-1/ [item1, item2,....], list-2/ [item1, item2,....], .......)
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
26
CSEA, IGIT, Sarang
EXAMPLES
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
27
CSEA, IGIT, Sarang
LISTS TUPLES
It is mutable. It is immutable.
Iterative process is slow. Iterative process is faster.
It is represented by square It is represented by brackets ( ).
brackets [ ].
It is useful for insertion and It is useful for read-only
deletion operations. operations like accessing
elements.
It consumes more memory. It consumes less memory.
It has several built-in methods. It has less built-in methods
because of immutability.
List operations are more error Tuples operations are safe.
prone.
Example: [1, 3, 4, 7] Example: (1, 3, 4, 7)
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
28
CSEA, IGIT, Sarang
DICTIONARY
It is a set of associations between a key and a value.
It is unordered, mutable (changeable) and indexed.
The keys must be unique but the values do not need to be
unique.
It is created using curly brackets ({ }) where each entry in
the dictionary is a key : value pair.
Syntax:
dictionary_name = {'key-1'/key-1 : value-1/'value-1', .........}
o value-1, value-2,....... are considered as numeric values.
o 'value-1', 'value-2',....... are considered as string values.
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
29
CSEA, IGIT, Sarang
EXAMPLES
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
30
CSEA, IGIT, Sarang
dict( ) FUNCTION
dict( ) function is used to create a new dictionary object
from an iterable or a sequence of key:value pairs.
SYNTAX-1:
dictionary_name = dict(**kwarg)
It takes a sequence of key:value pairs.
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
31
CSEA, IGIT, Sarang
dict( ) FUNCTION
SYNTAX-2: dictionary_name = dict(iterable, **kwarg)
It takes an iterable (List / Tuple) of key:value pairs and an
optional sequence of key:value pairs.
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
32
CSEA, IGIT, Sarang
dict( ) FUNCTION
SYNTAX-3: dictionary_name = dict(mapping, **kwarg)
It takes a mapping and a sequence of key:value pairs (optional).
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
33
CSEA, IGIT, Sarang
WORKING
WITH
DICTIONARIES
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
34
CSEA, IGIT, Sarang
ACCESSING Values via Keys
The values held in a Dictionary can be accessed using
their associated key.
The first way of accessing value is square bracket ([ ]).
SYNTAX:
dictionary_name[key_name]
The second way of accessing value is the get( ) method.
SYNTAX:
dictionary_name.get(key_name)
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
35
CSEA, IGIT, Sarang
EXAMPLES
Using Square Bracket ([ ])
Using get( ) Method
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
36
CSEA, IGIT, Sarang
ADDING A NEW Key:Value PAIR
A new key:value pair can be added to a dictionary by
providing the key in square brackets and the new value
to be assigned to that key.
SYNTAX:
dictionary_name['key_name'] = value / 'value'
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
37
CSEA, IGIT, Sarang
CHANGING/UPDATING Keys Value
The value associated with a key can be changed by
reassigning a new value using the square bracket ([ ])
or update( ) method.
Syntax of Assignment using Square Bracket([ ]):
dictionary_name['key_name'] = value / 'value'
Syntax of update( ) Method:
dictionary_name.update(key_name = value / 'value')
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
38
CSEA, IGIT, Sarang
EXAMPLES
Using Square Bracket ([ ])
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
39
CSEA, IGIT, Sarang
EXAMPLES
Using update( ) Method
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
40
CSEA, IGIT, Sarang
REMOVING Key : Value
A key:value pair can be removed from the dictionary in
three different ways.
(i) pop('key_name'):
• It removes the entry with the specified key.
• It returns the value of the key being deleted.
• SYNTAX:
variable = dictionary_name.pop('key_name')
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
41
CSEA, IGIT, Sarang
REMOVING Key : Value
(ii) popitem( ):
• It removes the last inserted item in the dictionary.
• It returns the deleted key:value pair.
• SYNTAX:
key_variable, value_variable = dictionary_name.popitem( )
(iii) del keyword:
• It removes the entry with the specified key from the
dictionary.
• It just deletes the item and does not return the associated
value.
• SYNTAX:
del dictionary_name['key_name']
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
42
CSEA, IGIT, Sarang
EXAMPLES
Using pop( ) Method
Using popitem( ) Method
Using del Keyword
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
43
CSEA, IGIT, Sarang
ITERATING OVER Keys
The 'for loop' processes each of the keys in the
dictionary.
This can be used to access each of the values associated
with the keys.
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
44
CSEA, IGIT, Sarang
ITERATING BOTH Keys and Values with items( ) METHOD
Dictionary key:value pairs can be iterated with the help of items( )
method.
SYNTAX of items( ) Method:
for key_variable, value_variable in dictionary_name.items( ):
Statement(s)
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
45
CSEA, IGIT, Sarang
in KEYWORD
It checks a key is a member of a dictionary or not.
SYNTAX:
variable_name = 'key_name' in dictionary_name
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
46
CSEA, IGIT, Sarang
len( ) FUNCTION
It counts the number of (key:value) pairs in a dictionary.
SYNTAX:
variable = len(dictionary_name / {'key-1': 'value-1', …..})
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
47
CSEA, IGIT, Sarang
keys( ), values( ), items( ) METHODS
keys( ) Method: It returns the list of keys of the dictionary.
SYNTAX:
list_name = dictionary_name.keys( )
values( ) Method: It returns the list of values of the
dictionary.
SYNTAX:
list_name = dictionary_name.values( )
items( ) Method: It returns the list of (key, value) tuples
of the dictionary.
SYNTAX:
tuple_name = dictionary_name.items( )
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
48
CSEA, IGIT, Sarang
EXAMPLES
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
49
CSEA, IGIT, Sarang
clear( ) METHOD
It empties the dictionary.
SYNTAX:
dictionary_name.clear( )
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
50
CSEA, IGIT, Sarang
COPYING A DICTIONARY
The copy a dictionary is done with the copy( ) method
and dict( ) constructor method.
SYNTAX of copy( ) Method:
new_dictionary_name = old_dictionary_name.copy( )
Syntax of dict( ) Constructor Method:
new_dictionary_name = dict(old_dictionary_name)
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
51
CSEA, IGIT, Sarang
EXAMPLES
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
52
CSEA, IGIT, Sarang
get( ) METHOD
It returns the value of the specified key.
SYNTAX:
variable_name = dictionary_name.get('key_name')
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
53
CSEA, IGIT, Sarang
del KEYWORD
It removes the item with the specified key name from the
dictionary.
SYNTAX:
del dictionary_name['Key_Name']
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
54
CSEA, IGIT, Sarang
TUPLES DICTIONARIES
It is a non-homogeneous data It is a non-homogeneous data
structure that can hold a single structure that contains key-value
row as well as several rows and pairs.
columns.
It is represented by brackets ( ). It is represented by curly
brackets { }.
It is immutable. It is mutable and do not allow
duplicate keys.
It is ordered. It is unordered.
It can be created using tuple() It can be created using dict()
constructor function. constructor function.
Example: Example:
('It', 'is', 'a', 'Tuple') {'Name':'CNU', 'Roll':71}
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
55
CSEA, IGIT, Sarang
SETS
A set is the collection of unordered elements.
Each element in the set must be unique, immutable, and the
sets remove the duplicate elements.
Sets are mutable which means it can be modified after its
creation.
A Set is defined using curly brackets ({ }).
(i) SYNTAX:
set_name = { element-1, element-2, ........... }
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
56
CSEA, IGIT, Sarang
EXAMPLES
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
57
CSEA, IGIT, Sarang
SETS
A set or an empty can also be created using set( ) constructor
function.
(ii) SYNTAX OF EMPTY SET:
set_name = set( )
(iii) SYNTAX OF SET CREATION:
set_name = set(set_name/{element-1, element-2, ......})
(iv) SYNTAX OF ITERABLE SET CREATION:
set_name = set(iterable)
• The iterable can be a List or Tuple or Dictionary or String.
• The keys set can be created from the dictionary by using the
'dictionary_name' or 'dictionary_name.keys( )'.
• Similarly, the values set can be created from the dictionary by
using the 'dictionary_name.values( )'.
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
58
CSEA, IGIT, Sarang
EXAMPLES
Example: Empty Set Creation using set( ) Constructor Function
Example: Set Creation using set( ) Constructor Function
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
59
CSEA, IGIT, Sarang
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
60
CSEA, IGIT, Sarang
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
61
CSEA, IGIT, Sarang
ACCESSING ELEMENTS IN A SET
Sets are unordered containers and thus there are
no indexes available.
Sets are Iterable containers.
Elements of a Set can be iterated over using the
'for' loop statement.
SYNTAX:
for variable_name in set_name:
Statement
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
62
CSEA, IGIT, Sarang
EXAMPLES
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
63
CSEA, IGIT, Sarang
WORKING
WITH
SETS
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
64
CSEA, IGIT, Sarang
add( ) METHOD
It adds an element in a non-empty set.
Syntax:
set_name.add(Element / 'Element')
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
65
CSEA, IGIT, Sarang
update( ) METHOD
It adds more than one element in a non-empty set.
Syntax:
set_name.update(List/Tuple/[Ele1/'Ele1',....]/(Ele1/'Ele1',....)/ Dictionary)
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
66
CSEA, IGIT, Sarang
update( ) METHOD
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
67
CSEA, IGIT, Sarang
update( ) METHOD
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
68
CSEA, IGIT, Sarang
remove( ) METHOD
It removes an item from a Set but generates an error if that
item was not found in the set.
SYNTAX:
set_name.remove(Element / 'Element')
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
69
CSEA, IGIT, Sarang
discard( ) METHOD
It removes an item from a Set but it does not generate an error
if that item was not found in the set.
SYNTAX:
set_name.discard(Element / 'Element')
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
70
CSEA, IGIT, Sarang
pop( ) METHOD
It removes the first item and returns the popped
item from the Set.
SYNTAX:
variable_name = set_name.pop( )
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
71
CSEA, IGIT, Sarang
clear( ) METHOD
It removes all the items from the Set and makes the set
empty.
SYNTAX:
set_name.clear( )
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
72
CSEA, IGIT, Sarang
in KEYWORD
It checks for the presence of an element in a set.
SYNTAX:
variable_name = Element / 'Element' in set_name
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
73
CSEA, IGIT, Sarang
len( ) FUNCTION
It returns the length of a set.
SYNTAX:
variable_name = len(set_name / {'Ele-1'/ Ele-1, .......})
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
74
CSEA, IGIT, Sarang
max( ) FUNCTION
It returns the maximum values in a set.
SYNTAX:
variable_name = max(set_name / {'Ele-1'/ Ele-1, .......})
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
75
CSEA, IGIT, Sarang
min( ) FUNCTION
It returns the minimum values in a set.
SYNTAX:
variable_name = min(set_name / {'Ele-1'/ Ele-1, .......})
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
76
CSEA, IGIT, Sarang
frozenset( ) FUNCTION
It converts a list ([ ]) and a set ({ }) to tuple kind (( )).
Finally, these tuples can be nested in a set.
SYNTAX OF LIST CONVERSION:
set_name = { frozenset ( List / ['Ele-1'/ Ele-1,...] ) }
SYNTAX OF SET CONVERSION:
set_name = { frozenset ( set_name / {'Ele-1'/ Ele-1,...} ) }
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
77
CSEA, IGIT, Sarang
EXAMPLES
PYTHON FOR ENGINEERS By Mr. Bapuji Rao,
78
CSEA, IGIT, Sarang