Unit-3_Collections and Sequences
Unit-3_Collections and Sequences
This document contains valuable confidential and proprietary information of ABESEC. Such confidential and
proprietary information includes, amongst others, proprietary intellectual property which can be legally protected and
commercialized. Such information is furnished herein for training purposes only. Except with the express prior
written permission of ABESEC, this document and the information contained herein may not be published,
disclosed, or used for any other purpose.
2
Copyright © 2021, ABES Engineering College
Objective of Collections/Sequences
To describe the importance of list , string, tuple , dictionary and set in python
3
Copyright © 2021, ABES Engineering College
Topics Covered
4
Copyright © 2021, ABES Engineering College
Topics Covered
5
Copyright © 2021, ABES Engineering College
Session Plan - Day 1
6
Copyright © 2021, ABES Engineering College
Introduction
7
Copyright © 2021, ABES Engineering College
Contd…
Representation of Python Collections with the help of Figure:
8
Copyright © 2021, ABES Engineering College
String
A string is a sequence of alphanumeric and
special character.
9
Copyright © 2021, ABES Engineering College
Creation of Empty String
Empty String
10
Copyright © 2021, ABES Engineering College
Creation of Non Empty String
11
Copyright © 2021, ABES Engineering College
Assessing the String
Positive Indexing
Negative Indexing
12
Copyright © 2021, ABES Engineering College
Positive Indexing
Positive indexing
start from Zero (0)
and from left hand
side i.e. first
character store at
index 0, second at
index 1 and so on.
Every character of
string has some
index value.
13
Copyright © 2021, ABES Engineering College
Negative Indexing
Negative
Indexing starts
from negative
indexing start
from -1 and
from right-hand
side.
Last character
store at index -
1 and as we
move towards
the left, it keeps
increasing like -
2, -3, and so
on.
14
Copyright © 2021, ABES Engineering College
Example
Write a program to print character 'P' and 'L' using positive indexing and negative indexing.
Assume a string st = 'I Like Python’, is given.
15
Copyright © 2021, ABES Engineering College
String Slicing
16
Copyright © 2021, ABES Engineering College
Syntax of String Slicing
17
Copyright © 2021, ABES Engineering College
Examples of String Slicing
st[ 2 : 6 ] It starts with the 2nd index and ending with (6It
starts with the 2nd index and ending with (6-1=5)th
index.-1=5)th index.
st[ 0 : 6 : 2 ] It starts with index 0th and end with (6-1=5) th. Step
is 2 So, it will give value at index 0,2,4
18
Copyright © 2021, ABES Engineering College
Contd..
19
Copyright © 2021, ABES Engineering College
Contd..
20
Copyright © 2021, ABES Engineering College
Important Points to Remember
Note about *, **
* When start index is missing it will start from either first character or from last. It
depends on step sign (positive or negative).
* When end index is missing it will execute till last character or first character. It depends
on step sign (positive or negative).
* When we take negative steps it will scan from start to end in opposite direction.
** In the case of step is positive or negative the slicing will be done as below given
algorithm.
21
Copyright © 2021, ABES Engineering College
Comparison
22
Copyright © 2021, ABES Engineering College
Updation in String
Strings in python are Immutable(un-changeable) sequences, which means it does not support new
element assignment using indexes.
In the above example string does not allow assigning a new element, because item assignment does
not support by string.
23
Copyright © 2021, ABES Engineering College
Contd..
1. What will be the output of the following code snippets?
A. come to Myso
B. come to Mys
C. lcome to Mys\
D. lcome to Myso
24
Copyright © 2021, ABES Engineering College
Contd..
2. What will be the output of the following code Comparison?
A. True
False
B. False
False
25
Copyright © 2021, ABES Engineering College
Contd..
3. What will be the output of the following code snippet?
A. ES
B. En
C. ES En
D. ESEn
26
Copyright © 2021, ABES Engineering College
Contd..
4. What will be the output of the following code snippet?
A. hellohowa
B. hellohowaaaaa
C. hellohowaaaaaaa
D. Error
27
Copyright © 2021, ABES Engineering College
Session Plan - Day 2
3.1 String
Built in Methods
Basic Operations
String Formatters
Loops with Strings
Review Questions
Practice Exercises
28
Copyright © 2021, ABES Engineering College
Deletion
In String, we can’t reassign the string characters but we can delete the complete string
using del command.
In the above example , after deletion when we try to print the string st it gives NameError : st not
defined.
29
Copyright © 2021, ABES Engineering College
String Built in methods:
30
Copyright © 2021, ABES Engineering College
String Built in methods:
31
Copyright © 2021, ABES Engineering College
String Built in methods:
32
Copyright © 2021, ABES Engineering College
String Built in methods:
33
Copyright © 2021, ABES Engineering College
String Built in methods:
34
Copyright © 2021, ABES Engineering College
String Built in methods:
Method Name Explanation Code Snippet
35
Copyright © 2021, ABES Engineering College
String Built in methods:
Method Name Explanation Code Snippet
36
Copyright © 2021, ABES Engineering College
String Built in methods:
37
Copyright © 2021, ABES Engineering College
Basic Operations in String:
38
Copyright © 2021, ABES Engineering College
Operations in String:
Method Name Explanation Code Snippet
+ Concatenation
* Multiply (Replicas)
It will repeat same string multiple
times and return.
Note – multiply string only with
integer number.
in Membership
It will check a given substring is
present in another string or not.
Note – gives bool value (True/False)
39
Copyright © 2021, ABES Engineering College
Operations in String:
Method Name Explanation Code Snippet
40
Copyright © 2021, ABES Engineering College
String Formatters:
String formatting is the process of infusing things in the string dynamically and presenting
the string.
Here, format implies that in what look and feel we want our strings to get printed.
41
Copyright © 2021, ABES Engineering College
String Formatters:
String formatting is the process of infusing things in the string dynamically and presenting
the string.
Here, format implies that in what look and feel we want our strings to get printed.
42
Copyright © 2021, ABES Engineering College
String format Style:
Escape Explanation Example
Sequence
\newline Ignores newline
\\ Backslash
43
Copyright © 2021, ABES Engineering College
String format Style
\n Newline
44
Copyright © 2021, ABES Engineering College
String Format()
We have placed two curly braces and arguments that give the format method filled in
the same output.
45
Copyright © 2021, ABES Engineering College
String Format()
46
Copyright © 2021, ABES Engineering College
String Format()
47
Copyright © 2021, ABES Engineering College
String Format()
48
Copyright © 2021, ABES Engineering College
String Format()
We can also use format specifier in format method like in language ‘C’. Format
specifier are used to do following.
49i
Copyright © 2021, ABES Engineering College
Format Specifiers
50
Copyright © 2021, ABES Engineering College
Format Specifiers
51
Copyright © 2021, ABES Engineering College
Formatting using f-string
Fstring is the way of formatting as format method does but in an easier way.
52
Copyright © 2021, ABES Engineering College
Can you answer these questions?
1. What will be the output of the following code snippet?
53
Copyright © 2021, ABES Engineering College
Can you answer these questions?
2. What will be the output of the following code snippet?
A. True
B. False
C. Error
D. None
54
Copyright © 2021, ABES Engineering College
Loops with Strings:
Strings are sequence of character and iterable objects, so we can directly apply for loop
through string.
Example-1 Example -2
Scan/Iterate each character of string through Scan/Iterate each character of string directly
index using for loop. using for loop
55
Copyright © 2021, ABES Engineering College
Loops with Strings:
Example 3 – Write a program to print number of alphabets and digits in a given string.
56
Copyright © 2021, ABES Engineering College
Loops with Strings:
Example 4
To add 'ing' at the end of a given string (length should be at least 3).
If the given string already ends with 'ing' then add 'ly' instead.
If the string length of the given string is less than 3, leave it unchanged.
57
Copyright © 2021, ABES Engineering College
Session Plan - Day 3
3.2 List
Creation
Accessing
Updation
Review Questions
Practice Exercises
58
Copyright © 2021, ABES Engineering College
List
59
Copyright © 2021, ABES Engineering College
List
60
Copyright © 2021, ABES Engineering College
List Example
61
Copyright © 2021, ABES Engineering College
Ordered Property of List
62
Copyright © 2021, ABES Engineering College
Creation of List
63
Copyright © 2021, ABES Engineering College
Accessing the List
It means last element can be accessed using -1 index, second last as -2 and so on.
64
Copyright © 2021, ABES Engineering College
Slicing
65
Copyright © 2021, ABES Engineering College
Slicing Example
67
Copyright © 2021, ABES Engineering College
Examples of List Slicing
68
Copyright © 2021, ABES Engineering College
Updation in List:
List updating involves insertion of new elements, deletion of elements or deletion of complete list.
69
Copyright © 2021, ABES Engineering College
Updation in List:
List updating involves insertion of new elements, deletion of elements or deletion of complete
list.
70
Copyright © 2021, ABES Engineering College
Can you answer these Questions
A.[‘XY’,’YZ’]
B.[‘xy’,’yz’]
A. [‘g’,’h’,’k’,’l’,’m’]
B. [‘g’,’h’,’k’,’l’,’m’,9]
C. [‘g’,’h’,’k’,’l’,’m’,8,9]
D. [‘g’,’h’,’k’,’l’,’m’,9,8]
72
Copyright © 2021, ABES Engineering College
Session Plan - Day 4
3.2 List
Updation in List
Operations in List
Built in Methods
Operations
Loops
Nested list
List Comprehension
Review Questions
Practice Exercises
73
Copyright © 2021, ABES Engineering College
Add new element in List:
Append function always add the element at the end of the list.
Syntax:
74
Copyright © 2021, ABES Engineering College
Changing new element in List:
Value of the element at index 3 has been assigned new value as 5, so element in the output
list is changed from 4 to 5.
75
Copyright © 2021, ABES Engineering College
Deletion in List:
Using del command If we know the position(index) of the element which is to be deleted.
We can use the remove method by giving the specific element as given in the example If we know the
position(index) of the element.
76
Copyright © 2021, ABES Engineering College
Deletion in List:
list1 has been deleted and then we are trying to print it and its giving error because
it does not exist now.
77
Copyright © 2021, ABES Engineering College
Built in Methods in List
78
Copyright © 2021, ABES Engineering College
Contd..
79
Copyright © 2021, ABES Engineering College
Operations on List
80
Copyright © 2021, ABES Engineering College
Contd..
81
Copyright © 2021, ABES Engineering College
Example
82
Copyright © 2021, ABES Engineering College
Practice Problems
Take a list input from user having integer elements and calculate sum and average of the
list.
Take an input list and swap string elements of the list with empty string.
83
Copyright © 2021, ABES Engineering College
Loops with List
84
Copyright © 2021, ABES Engineering College
Example
Practice Exercise:
Write a python program to count positive, negative and string type elements.
85
Copyright © 2021, ABES Engineering College
Nested List
When we have an element of a list in the form of the list itself, it is called Nested List.
Elements of the nested list can be accessed using the 2-D indexing access method.
In this example, first [1] denotes [3,4] and second [1] represents 4, so it gives output as 4.
86
Copyright © 2021, ABES Engineering College
Nested List as a Matrix
Outer loop would run for number of elements in the list and inner loop would consider
individual element of the nested list as a list.
87
Copyright © 2021, ABES Engineering College
Example
.
Practice Exercise:
Using nested list print transpose, of a given matrix
88
Copyright © 2021, ABES Engineering College
List Comprehensions
Let's suppose we want to write a program to calculate powers of 3 for a given range.
89
Copyright © 2021, ABES Engineering College
List Comprehension
Syntax:
IF ELSE :
[ statements for an item in list ]
We should notice one change that because in if-else
case output is separated based on the condition.
We have the facility of adding conditionals in
if-else and conditions has been written along with
the list comprehension. statements.
90
Copyright © 2021, ABES Engineering College
Session Plan - Day 5
3.3 Tuple
• Creation
• Assessing
• Modification/Updation
• Built in Methods
• Operations
• Review Questions
• Practice Exercises
91
Copyright © 2021, ABES Engineering College
Session Plan - Day 5
3.3 Tuple
• Creation
• Assessing
• Modification/Updation
• Built in Methods
• Operations
• Review Questions
• Practice Exercises
92
Copyright © 2021, ABES Engineering College
Tuple
Generally, when we have data to process, it is not required to modify the data values.
Take an example of week days, here the days are fixed. So, it is better to store the values in the data
collection, where modification is not required.
93
Copyright © 2021, ABES Engineering College
Creation of Tuple
94
Copyright © 2021, ABES Engineering College
Example
If you want to create a tuple with single value, it is required to add a comma after the single value as
shown in the above example c=(‘college’,).
If the comma is not placed, then the single value a= (1) or b=(ABES) will be treated as an
independent value instead of the data collection.
.
95
Copyright © 2021, ABES Engineering College
Packing and Unpacking of Tuple
96
Copyright © 2021, ABES Engineering College
Unpacking of Tuple
Unpacking is called when the multiple variables is assigned to a tuple; then these variables take
corresponding values.
Practice Questions:
97
Copyright © 2021, ABES Engineering College
Accessing Elements in Tuple
Tuple elements can be accessed using indexes, just like String and List .
Each element in the tuple is accessed by the index in the square brackets [].
Example:
In above example 1: tuple newtup carries multiple types of data in it as “hello” is string, 2 is integer, and
.
23.45 is float. If we can fetch the index 1 element using print(newtup[1]).
98
Copyright © 2021, ABES Engineering College
Contd…
Indexes start from zero, and it goes up to a number of elements or say -1.
99
Copyright © 2021, ABES Engineering College
Indexing in Tuple and Slicing
Slicing in a tuple is like a list that extracts a part of the tuple from the original tuple.
100
Copyright © 2021, ABES Engineering College
Modification/Updating a Tuple
If we want to change any of the index value in tuple, this is not allowed and throw an error.
Here, we are taking the same above example of days and showing the immutable
characteristic of tuple
101
Copyright © 2021, ABES Engineering College
Practice Exercises
Write a Python program to get the 4th element and 4th element from last of a tuple.
102
Copyright © 2021, ABES Engineering College
Built in Methods in Tuple
103
Copyright © 2021, ABES Engineering College
Operations on Tuple
To check whether an
Membership element belong to tuple
or not
104
Copyright © 2021, ABES Engineering College
Loops and Conditions on Tuples
Take the tuple named tuple_days and print all its elements
In this example The elements are printed while iterating through for loop condition for in tuple_days and then
we print the values of i in each iteration.
105
Copyright © 2021, ABES Engineering College
Loops and Conditions on Tuples
Example:
Let have a look to the example where we are placing a condition to return the values
having word length greater than 3.
In above example , The elements are printed while iterating through for loop condition for in tuple_days
and then we print the values of i in each iteration with the condition if(len(i)>3)
106
Copyright © 2021, ABES Engineering College
Comparison between List and Tuple
List Tuple
Mutable Sequence Immutable Sequence
Accession Slower than Tuple because of Faster access of elements due to
mutable property immutable property
It cannot be used as Dictionary keys Can work as a key of the dictionary
Not suitable for application which needs It suits such scenarios where write
write protection protection is needed.
107
Copyright © 2021, ABES Engineering College
Session Plan - Day 6
3.4 Dictionaries
• Creation
• Assessing
• Modification/Updation
• Nested Dictionary
• Built in Methods
• Review Questions
• Practice Exercises
108
Copyright © 2021, ABES Engineering College
Dictionaries
109
Copyright © 2021, ABES Engineering College
Introduction
110
Copyright © 2021, ABES Engineering College
Example-1
Creating an empty dictionary
111
Copyright © 2021, ABES Engineering College
Example-2
Creating a non-empty dictionary
112
Copyright © 2021, ABES Engineering College
Accessing of Dictionary
In dictionary, the items are accessed by the keys.
113
Copyright © 2021, ABES Engineering College
Can you answer these questions?
A) ‘Java’
B) ‘Python’
C) KeyError
D) None of above
114
Copyright © 2021, ABES Engineering College
Can you answer these questions?
A) 5
B) 10
C) 15
D) None of above
115
Copyright © 2021, ABES Engineering College
Accessing of Dictionary
List Dictionary
116
Copyright © 2021, ABES Engineering College
Modification in a Dictionary
117
Copyright © 2021, ABES Engineering College
Can you answer these questions?
A) {1:’Store’,2:’Kitchen’}
B) {2:’Store’,1:’Kitchen’}
C)KeyError
D) None of above
118
Copyright © 2021, ABES Engineering College
Can you answer these questions?
A) True
B) False
119
Copyright © 2021, ABES Engineering College
Nested Dictionary
As we have the option of a nested list, similarly, dictionaries can consist of
data collections.
120
Copyright © 2021, ABES Engineering College
Session Plan - Day 7
3.4 Dictionary
• Built in Methods in Dictionary
• Loops in Dictionary
• Review Questions
• Practice Exercises
121
Copyright © 2021, ABES Engineering College
Built-in Methods in Dictionary
Method Description
fromkeys() Create a new dictionary with key in a data sequence list/tuple with value
get() If the key is present in the dictionary, its value is returned. If the key is not present in a dictionary, then
the default value will be shown as output instead of a KeyError.
items() this will return the key-value pair as an output.
pop() The pop() method takes an argument as the dictionary key, and deletes the item from the dictionary.
popitem() The popitem() method retrieves and removes the last key/value pair inserted into the
dictionary.
122
Copyright © 2021, ABES Engineering College
copy()
copy() method provide a fresh copy with different memory location.
Output
123
Copyright © 2021, ABES Engineering College
fromkey()
Output
124
Copyright © 2021, ABES Engineering College
get()
Output
125
Copyright © 2021, ABES Engineering College
items(),keys(),values()
Output
126
Copyright © 2021, ABES Engineering College
update()
Output
127
Copyright © 2021, ABES Engineering College
pop(),popitem()
Output
128
Copyright © 2021, ABES Engineering College
Can you answer these questions?
A) {1:1,2:4,3:9,4:16,5:25,6:36}
B) {1:1,2:4,3:9,4:16,5:25}
C) [1,4,9,16,25]
D) Error
129
Copyright © 2021, ABES Engineering College
Can you answer these questions?
A) {1:’Store’,2:’Kitchen’}
B) {2:’Store’,1:’Kitchen’}
C)KeyError
D) None of above
130
Copyright © 2021, ABES Engineering College
Session Plan - Day 8
3.5 Set
• Creation
• Assessing
• Modification
• Built in methods
• Operators
• Loops
• Frozen Set
• Review Questions
131
Copyright © 2021, ABES Engineering College
Set
132
Copyright © 2021, ABES Engineering College
Creation of empty Set
133
Copyright © 2021, ABES Engineering College
Creation of non-empty Set
134
Copyright © 2021, ABES Engineering College
Creation of non-empty Set
135
Copyright © 2021, ABES Engineering College
Can you answer these questions?
A) True
B) False
136
Copyright © 2021, ABES Engineering College
Accessing set
137
Copyright © 2021, ABES Engineering College
Built-in Methods in Dictionary
Method Description
update() If the key is present in the dictionary, its value is returned. If the key is not present in a dictionary, then
the default value will be shown as output instead of a Key Error.
remove() to remove the specified element from the given set.
pop() used to removes a random element from the set and returns the popped (removed) elements.
remove () used to remove the specified element from the given set.
discard () used to remove the specified item from the given input set. the remove() method will give an error if
the specified item does not exist but this method will not.
138
Copyright © 2021, ABES Engineering College
copy()
copy() method provide a fresh copy with different memory location.
139
Copyright © 2021, ABES Engineering College
clear()
140
Copyright © 2021, ABES Engineering College
add()
141
Copyright © 2021, ABES Engineering College
update()
142
Copyright © 2021, ABES Engineering College
remove()
143
Copyright © 2021, ABES Engineering College
discard()
144
Copyright © 2021, ABES Engineering College
Operators
Set Operation Description Operator Method
Difference Elements that are present in one set, but not the other - difference()
Symmetric Difference Elements present in one set or the other, but not both ^ symmetric_difference()
Disjoint True if the two sets have no elements in common None isdisjoint()
True if one set is a subset of the other (that is, all
Subset <= issubset()
elements of set2 are also in set1)
145
Copyright © 2021, ABES Engineering College
Union
146
Copyright © 2021, ABES Engineering College
Intersection
147
Copyright © 2021, ABES Engineering College
Intersection
148
Copyright © 2021, ABES Engineering College
Set Difference
149
Copyright © 2021, ABES Engineering College
Symmetric Difference
150
Copyright © 2021, ABES Engineering College
Loops with set
151
Copyright © 2021, ABES Engineering College
Frozen Set
A frozen set is a special category of the set which is unchangeable once created
152
Copyright © 2021, ABES Engineering College
Frozen Set
153
Copyright © 2021, ABES Engineering College
Summary
List Tuple Set Dictionary
List is a collection of values Tuple is ordered and Set stores the unique values Dictionary is a collection of
that is ordered. unchangeable collection of as data collection key-value pairs
values
Represented by [ ] Represented by ( ) Represented by { } Represented by { }
Duplicate elements allowed Duplicate elements allowed Duplicate elements not Duplicate keys not allowed, in
allowed dictionary values allowed
duplicate
Values can be of any type Values can be of any type Values can be of any type Keys are immutable type, and
value can be of any type
Example: Example: Example: Example:
[1, 2, 3, 4] (1, 2, 3, 4) {1, 2, 3, 4} {1:1, 2:2, 3:3, 4:4}
List is mutable Tuple is immutable Set is mutable Dictionary is mutable
Creating an empty list Creating an empty Tuple Creating a set Creating an empty dictionary
l=list() t = tuple () s=set () d=dict( )
l = [] t=( ) d={}
154
Copyright © 2021, ABES Engineering College
Can you answer these questions?
A) iii
B) i and ii
C) ii and iii
D) All of Above
155
Copyright © 2021, ABES Engineering College
Can you answer these questions?
A) {0,0,9}
B) {0,9}
C) {9}
D) Error
156
Copyright © 2021, ABES Engineering College
Can you answer these questions?
157
Copyright © 2021, ABES Engineering College