6.PythonProgramming Module 4
6.PythonProgramming Module 4
Data Collections
[Link]@[Link] (Personal)
[Link]@[Link] (Official)
+91-8220417476
Python Strings 1
▶ We can use the negative indexes to start the slice from the end of the string
▶ To get the characters from 5 to position 1 (not included) counted from
backwards, we cause the following command:
1 s = ' Hello World ! '
2 print ( s [ -5: -2])
▶ Please recall that, we cannot combine strings and numbers directly in Python
i.e., the code:
1 age = 36
2 name = " Tom "
3 txt = name + " age is : " + age
4 print ( txt )
returns an error.
▶ One way to overcome is to convert the integer into string:
1 age = 36
2 name = " Tom "
3 txt = name + " age is : " + str ( age )
4 print ( txt )
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
String Format 7
▶ The format() method takes unlimited number of arguments, and are placed
into the respective placeholders:
1 name = " Tom "
2 age = 36
3 txt = " {} age is : {} "
4 print ( txt . format ( name , age ))
▶ We can use index numbers {0} to be sure the arguments are placed in the
correct placeholders:
1 age = 36
2 name = " Tom "
3 txt = " {1} age is : {0} "
4 print ( txt . format ( age , name ))
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
String Format 9
1 quantity = 3
2 itemno = 567
3 price = 4000.60
4 myorder = " We need to by {2} items each of quantity {1}
and I have a total of {0} rupees with me ."
5 print ( myorder . format ( price , quantity , itemno ))
Quotation Marks in f-string: To use any type of quotation marks with the
f-string in Python, we have to make sure that the quotation marks used inside
the expression are not the same as quotation marks used with the f-string.
1 print ( f " 'M . Sc Data Science '")
2
f-strings can be used in input to dynamically display the message and take the
input from the user.
1 name = " Tom "
2 data = input ( f" Hi ... { name }. Please enter your best
friends name :")
3 # The above line echoes
4 # Hi ... Tom . Please enter your best friends name :
5 name = " Jerry "
6 data = input ( f" Hi ... { name }. Please enter your best
friends name :")
7 # The above line echoes
8 # Hi ... Jerry . Please enter your best friends name :
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
String Methods 15
▶ split() – this method splits the string into substrings if it finds the instance
of the separator/character we have supplied and omitting that
separator/character.
1 s = " Hello , World !"
2 print ( s . split (" ,")) # Prints "[ ' Hello ', ' World ! ']"
3 print ( s . split (" ")) # Prints "[ ' Hello ,', ' World ! ']"
4 print ( s . split ("o")) # Prints "[ ' Hell ', ' , W ', ' rld
! ']"
▶ strip() – This method removes any whitespace from the beginning or the
end of the string
1 s = " Hello World ! "
2 print ( s . strip () ) # returns " Hello World !"
▶ lower() – This method returns the string in lower case
▶ upper() – This method returns the string in upper case
▶ capitalize() – This method converts the first character to upper case
▶ title() – This method returns the string in title case i..e, the first character
of each word in upper case.
▶ swapcase() – This methods swaps cases, lower case by upper case and vice
versa
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
String Methods 19
There are four collection data types in the Python programming language:
▶ List is a collection which is ordered and changeable (mutable). Allows
duplicate members.
▶ Tuple is a collection which is ordered and unchangeable (immutable). Allows
duplicate members.
▶ Set is a collection which is unordered and unindexed (mutable). No duplicate
members.
▶ Dictionary is a collection which is ordered1 , changeable and indexed
(mutable). No duplicate members.
1
As of Python 3.7 and later dictionaries are ordered. In Python 3.6 and earlier dictionaries are
unordered
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Python Lists 23
In Pyhton a list is a collection which is ordered and changeable. In Python lists are
written with square brackets.
1 myList = [ " First " , " Second " , " Third " , " Fourth " , " Fifth "
]
2 print ( myList )
3
1 myFruits = [ " apple " , " banana " , " cherry " , " orange " , "
kiwi " , " melon " , " mango "]
2 print ( myFruits [2:5]) # Prints the elements starts with
index 2 and upto index 5 ( not included )
3
3 myFruits [1] = " grape " # Changes the entry in the index
1
4 print ( myFruits )
5
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the cur-
rent list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Tuples 27
You cannot add or delete or change the elements of a tuple. To change them we
need to convert a tuple into a list.
1 myList = list ( myFruits )
2 print ( myList )
3 myList [1] = " organge "
4 myFruits = tuple ( myList )
5 print ( myFruits )
4 # NOT a tuple
5 mytuple = ( " apple ")
6 print ( type ( mytuple ))
1 myfruits = { " apple " , " banana " , " cherry "}
2 print ( myfruits )
3
4 for x in myfruits :
5 print ( x )
6
1 myfruits = { " apple " , " banana " , " cherry "}
2 myfruits . add ( " orange ")
3 print ( myfruits )
4
5 myfruits . update ([ " orange " , " mango " , " grapes " ])
6 print ( myfruits )
7
4 x = myfruits . pop ()
5 print ( x )
6 print ( myfruits )
7
8 myfruits . clear ()
9 print ( myfruits )
10
11 myfruits = { " apple " , " banana " , " cherry "}
12 del myfruits
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Python Sets 38
Method 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 an-
other, 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
Method Description
issubset() Returns whether another set contains this set or
not
issuperset() Returns whether this set contains another set or
not
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_update() inserts the symmetric differences from this set and
another
union() Return a set containing the union of sets
update() Update the set with the union of this set and others
11 print ( set5 )
12 print ( set6 )
13
1 myDict = {
2 " brand " : " HP " ,
3 " btype " : " Convertible " ,
4 " byear " : 2019
5 }
6 print ( myDict )
4 # Output : { ' a ': ' Alpha ', 'b ': ' Beta ', 'g ': ' Gamma '}
5
6 dictionary_unique = {"a": " Alpha " , "b": " Beta " , "g": "
Gamma " , " g " : " Omega "}
7 print ( dictionary_unique )
8
9 # Output : { ' a ': ' Alpha ', 'b ': ' Beta ', 'g ': ' Omega '}
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Python Dictionaries
Accessing Keys and Values 45
If we want to access both the key, value pair, we could use .items() method,
which will return a list of dict_items in the form of key, value tuple pairs.
1 ditems = dictionary_unique . items ()
2 print ( ditems )
3
To change the value of a specific item we refer to its key name: For example to
change the "brand" to "Lenovo" we can use
1 myDict [ " brand "] = " Lenovo "
2 print ( myDict )
To remove an item from dictionary we can use pop() method and by passing the
key name:
1 myDict = {
2 " brand " : " Lenovo " ,
3 " btype " : " Tablet " ,
4 " byear " : 2019
5 }
6 myDict . pop ( " btype ")
7 print ( myDict )
The method popitem() removes the last inserted item (In Python versions before
3.7, this method removes a random item)
1 myDict = {
2 " brand " : " Lenovo " ,
3 " btype " : " Tablet " ,
4 " byear " : 2019
5 }
6 myDict . popitem ()
7 print ( myDict )
The copy() command will be useful in making a copy of the dictionary already
existing.
1 myDict = {
2 " brand " : " Lenovo " ,
3 " btype " : " Tablet " ,
4 " byear " : 2019
5 }
6 print ( myDict )
7 myDict2 = myDict . copy ()
8 print ( myDict2 )
Another method
1 prod1 = {
2 " bname ": " HP " ,
3 " btype ": " Computer " ,
4 " byear ": 2019
5 }
6 prod2 = {
7 " bname ": " Lenovo " ,
8 " btype ": " Tablet " ,
9 " byear " :2019
10 }
11 prod3 = {
12 " bname ": " Microsoft " ,
13 " btype ": " Convertible " ,
14 " byear ": 2020
15 }
16
17 myDict = {
18 " prod1 ": prod1 ,
19 " prod2 ": prod2 ,
20 " prod3 ": prod3
21 }
22 print ( myDict )
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Python Dictionaries
Nested Dictionaries 54
1 for x in myDict :
2 print ( x ) # Prints the key
3 print ( myDict [x ]) # Prints the value
We can also use values() function to return the values of a dictionary:
1 for x in myDict . values () :
2 print ( x ) # Prints the value
To loop through keys and values we can use items() function
1 for x , y in myDict . items () :
2 print (x , y) # Prints the key , value
We can combine the for loop and dictionary data type in Python to count the word
frequency in a string.
1 rand_str = ' Video provides a powerful way to help you prove
your point . \
2 When you click Online Video you can paste in the embed
code for the video you want to add . '
3
4 word_freq = dict ()
5 rand_str_word = str ( rand_str ). split ()
6 for word in range ( len ( rand_str_word )) :
7 if rand_str_word [ word ] not in word_freq :
8 word_freq [ rand_str_word [ word ]] = 1
9 else :
10 word_freq [ rand_str_word [ word ]] += 1
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Python List Comprehension 57
V = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096};
M = {0, 4, 16, 36, 64}
1 S = []
2 for x in range (10) :
3 S. append (x **2)
4 print (S )
5
6 V = []
7 for i in range (13) :
8 V. append (2** i)
9 print (V)
10
11 M = []
12 for x in S:
13 if x %2 == 0:
14 M . append (x)
15 print (M)
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Python List Comprehension 59
the Python code using the for loop and list comprehension is:
1 M = [] 1 M = [[4* i + j for j in range
2 for i in range (4) : (1 ,5) ] for i in range (4) ]
3 M . append ([]) 2 print ( M )
4 for j in range (1 ,5) : 3 # Output : [[1 , 2 , 3 , 4] , [5 ,
5 M[ i ]. append (4* i+ j) 6 , 7, 8] , [9 , 10 , 11 , 12] ,
6 print ( M ) [13 , 14 , 15 , 16]]
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Python Set Comprehension 65
3 print ( set_comprehension )
4