Python Collections: Lists, Strings, Tuples, Dictionaries, Sets
Python Collections: Lists, Strings, Tuples, Dictionaries, Sets
To describe the importance of list , string, tuple , dictionary and set in python
3
Topics Covered
4
Topics Covered
5
Session Plan - Day 1
6
Introduction
7
Contd…
Representation of Python Collections with the help of Figure:
8
String
❑ A string is a sequence of alphanumeric and
special character.
9
Creation of Empty String
Empty String
❑ An empty string is a string having no
character.
❑ We have three ways to create an empty
string as shown in syntax.
❑ An Empty String is created by single quotes,
double quotes and str().
10
Creation of Non Empty String
11
Assessing the String
❖ Positive Indexing
❖ Negative Indexing
12
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
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
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
String Slicing
16
Syntax of String Slicing
17
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
Contd..
19
Contd..
20
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
Comparison
22
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
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
Contd..
2. What will be the output of the following code Comparison?
A. True
False
B. False
False
25
Contd..
3. What will be the output of the following code snippet?
A. ES
B. En
C. ES En
D. ESEn
26
Contd..
4. What will be the output of the following code snippet?
A. hellohowa
B. hellohowaaaaa
C. hellohowaaaaaaa
D. Error
27
Session Plan - Day 2
1. String
▪ Built in Methods
▪ Basic Operations
▪ String Formatters
▪ Loops with Strings
▪ Review Questions
▪ Practice Exercises
28
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
String Built in methods:
30
String Built in methods:
31
String Built in methods:
32
String Built in methods:
33
String Built in methods:
34
String Built in methods:
Method Name Explanation Code Snippet
35
String Built in methods:
Method Name Explanation Code Snippet
36
String Built in methods:
37
Basic Operations in String:
38
Operations in String:
Method Name Explanation Code Snippet
+ Concatenation
in Membership
It will check a given substring is
present in another string or not.
Note – gives bool value (True/False)
39
Operations in String:
Method Name Explanation Code Snippet
40
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
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
String format Style:
Escape Explanation Example
Sequence
\newline Ignores newline
\\ Backslash
43
String format Style
\n Newline
44
String Format()
❑ We have placed two curly braces and arguments that give the format method filled in
the same output.
45
String Format()
46
String Format()
47
String Format()
48
String Format()
❑ We can also use format specifier in format method like in language ‘C’. Format
specifier are used to do following.
49i
Format Specifiers
50
Format Specifiers
51
Formatting using f-string
❑ Fstring is the way of formatting as format method does but in an easier way.
52
Can you answer these questions?
1. What will be the output of the following code snippet?
53
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
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
Loops with Strings:
Example 3 – Write a program to print number of alphabets and digits in a given string.
56
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
Session Plan - Day 3
3.2 List
▪ Creation
▪ Accessing
▪ Updation
▪ Review Questions
▪ Practice Exercises
58
List
59
List
60
List Example
61
Ordered Property of List
62
Creation of List
63
Accessing the List
❑ It means last element can be accessed using -1 index, second last as -2 and so on.
64
Slicing Example
❑ 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
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
Example
.
Practice Exercise:
❑ Using nested list print transpose, of a given matrix
88
List Comprehensions
❑ Let's suppose we want to write a program to calculate powers of 3 for a given range.
89
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
Can you answer these questions?
A.[0,1,2,3,4,5]
B.[0,1,2,3,4,5,6]
C.[0,1,2,3]
91
Can you answer these questions?
A. [5,7,9]
B.[3,4,5]
C.[6,7,8]
. D.[9,10,11]
92
Session Plan - Day 5
3.3 Tuple
• Creation
• Assessing
• Modification/Updation
• Built in Methods
• Operations
• Review Questions
• Practice Exercises
93
Session Plan - Day 5
3.3 Tuple
• Creation
• Assessing
• Modification/Updation
• Built in Methods
• Operations
• Review Questions
• Practice Exercises
94
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.
95
Creation of Tuple
96
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.
.
97
Packing and Unpacking of Tuple
98
Unpacking of Tuple
❑ Unpacking is called when the multiple variables is assigned to a tuple; then these variables take
corresponding values.
Practice Questions:
99
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 [].
❑ An index starts with zero and ends with (number of elements - 1)
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]).
100
Contd…
❑ Indexes start from zero, and it goes up to a number of elements or say -1.
101
Indexing in Tuple and Slicing
❑ Slicing in a tuple is like a list that extracts a part of the tuple from the original tuple.
102
Modification/Updating a Tuple
❑ If we want to change any of the index value in tuple, this is not allowed and throw an error.
103
Practice Exercises
❑ Write a Python program to get the 4th element and 4th element from last of a tuple.
104
Built in Methods in Tuple
105
Operations on Tuple
To check whether an
Membership element belong to tuple
or not
106
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.
107
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)
108
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.
109
Practice Exercises:
Exercise: Write Python program to join two input tuples, if their first element is common.
110
Session Plan - Day 6
3.4 Dictionaries
• Creation
• Assessing
• Modification/Updation
• Nested Dictionary
• Built in Methods
• Review Questions
• Practice Exercises
111
Dictionaries
112
Introduction
113
Example-1
▪ Creating an empty dictionary
114
Example-2
▪ Creating a non-empty dictionary
115
Accessing of Dictionary
➢ In dictionary, the items are accessed by the keys.
116
Can you answer these questions?
A) ‘Java’
B) ‘Python’
C) KeyError
D) None of above
117
Can you answer these questions?
A) 5
B) 10
C) 15
D) None of above
118
Accessing of Dictionary
List Dictionary
119
Modification in a Dictionary
120
Can you answer these questions?
A) {1:’Store’,2:’Kitchen’}
B) {2:’Store’,1:’Kitchen’}
C)KeyError
D) None of above
121
Can you answer these questions?
A) True
B) False
122
Nested Dictionary
➢ As we have the option of a nested list, similarly, dictionaries can consist of
data collections.
123
Session Plan - Day 7
3.4 Dictionary
• Built in Methods in Dictionary
• Loops in Dictionary
• Review Questions
• Practice Exercises
124
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.
125
copy()
➢ copy() method provide a fresh copy with different memory location.
Output
126
fromkey()
Output
127
get()
Output
128
items(),keys(),values()
Output
129
update()
Output
130
pop(),popitem()
Output
131
Loops and conditions on dictionaries
➢ Loops and conditions can easily apply to dictionaries.
dict1={1:1,2:4,4:8,6:36}
for key in [Link](): for val in [Link](): for item in [Link](): for i,j in [Link]():
print(key) print(val) print(item) print(i,":",j)
OUTPUT
1 1 (1,1) 1:1
2 4 (2,4) 2:4
4 8 (4,8) 4:8
6 36 (6,36) 6:36
132
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
133
Can you answer these questions?
A) {1:’Store’,2:’Kitchen’}
B) {2:’Store’,1:’Kitchen’}
C)KeyError
D) None of above
134
Session Plan - Day 8
3.5 Set
• Creation
• Assessing
• Modification
• Built in methods
• Operators
• Loops
• Frozen Set
• Review Questions
135
Set
136
Creation of empty Set
137
Creation of non-empty Set
138
Creation of non-empty Set
139
Can you answer these questions?
A) True
B) False
140
Accessing set
141
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.
142
copy()
➢ copy() method provide a fresh copy with different memory location.
143
clear()
144
add()
145
update()
146
remove()
147
pop()
148
update()
149
remove()
150
discard()
151
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)
True if one set is a subset of the other,
Proper Subset < None
but set2 and set1 cannot be identical
152
Union
153
Intersection
154
Intersection
155
Set Difference
156
Symmetric Difference
157
Loops with set
158
Frozen Set
A frozen set is a special category of the set which is unchangeable once created
159
Frozen Set
160
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={}
161
Can you answer these questions?
A) iii
B) i and ii
C) ii and iii
D) All of Above
162
Can you answer these questions?
A) {0,0,9}
B) {0,9}
C) {9}
D) Error
163
Can you answer these questions?
164