[Go to site: main page, start]

0% found this document useful (0 votes)
4 views69 pages

6.PythonProgramming Module 4

The document provides an overview of Python programming focusing on strings and data collections. It covers string literals, string methods, string formatting, and introduces collection types such as lists, tuples, sets, and dictionaries. Additionally, it includes examples and explanations of various string operations and methods in Python.

Uploaded by

sjlkuikel
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views69 pages

6.PythonProgramming Module 4

The document provides an overview of Python programming focusing on strings and data collections. It covers string literals, string methods, string formatting, and introduces collection types such as lists, tuples, sets, and dictionaries. Additionally, it includes examples and explanations of various string operations and methods in Python.

Uploaded by

sjlkuikel
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PMDS508L - Python Programming

Data Collections

Dr. B.S.R.V. Prasad


Department of Mathematics
School of Advanced Sciences
Vellore Institute of Technology
Vellore

[Link]@[Link] (Personal)
[Link]@[Link] (Official)
+91-8220417476
Python Strings 1

▶ String literals in Python are surrounded by either single quotes or double


quotes.
▶ Example: a = 'Hello' is same as a = "Hello"
▶ Multiline Strings:
1 a = " " " This is a long string ,
2 This is the second line of the string ,
3 This is the last line of the string ."""
4 print ( a )
▶ We can also use three single quotes instead of three double quotes.
▶ Note that, the line breaks are inserted at the same position as in the code.
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Strings as Arrays 2

▶ Strings in Python are represented as arrays of bytes of unicode characters.


▶ In Python we don’t have a character data type, a single character is simply as
string of length 1.
▶ Square brackets can be used to access elements of the string.
1 s = " Hello World !"
2 print ( s [1])
3 print ( s [3])
Please note that in Python the index starts with 0 not with 1
▶ The Length of the string can be found by using len() command. len(s)
gives the length of the string s.
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
String Slicing 3

▶ We can return a range of characters by using the slice syntax.


▶ For slicing the string and return the part of the string, we need to specify the
start index and end index, separated by a colon.
▶ The end index character will not be included in the sliced string i.e., the string
returned will begin from the start index character and till up to the end-1
character.
1 s = ' Hello World ! '
2 print ( s [2:5])

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Negative Indexing in Strings 4

▶ 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])

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


String Concatenation 5

▶ To concatenate, or combine, strings we can use + operator.


1 a = " Hello "
2 b = " World !"
3 c = a+b
4 print ( c ) # Prints " HelloWorld !"
5 c = a + " " + b
6 print ( c ) # Prints " Hello World !"

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


String Format 6

▶ 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

▶ Another way to combine strings and number is by using format() method.


▶ The format() method takes the passed arguments, formats them, and
places them in the string where the placeholders {} are:
1 age = 36
2 txt = " Tom age is : {} "
3 print ( txt . format ( age ))

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


String Format 8

▶ 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 ))

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


f-strings in Python 10

▶ Python offers a powerful feature called f-strings (formatted string literals) to


simplify string formatting and interpolation.
▶ f-strings is introduced in Python 3.6.
▶ f-strings provide a concise and intuitive way to embed expressions and
variables directly into strings.
▶ To create an f-string, prefix the string with the letter “f”.

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


f-strings in Python 11

1 val1 = " Data "


2 val2 = " Science "
3 print ( f " { val1 } { val2 } is the study of { val1 }. ")
4

6 name = ' Tom '


7 age = 22
8 print ( f " Hello ... My name is { name } and I 'm { age } years
old . " )

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


f-strings in Python 12

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

3 print ( f " " " M . Sc " Data " Sciences """)


4

5 print ( f ' ' 'M . Sc ' Data ' Science ''')


6

7 print ( f 'M . Sc " Data " Science ')

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


f-strings in Python 13

Evaluate Expressions with f-Strings: We can also evaluate expressions with


f-strings in Python. To do so, we have to write the expression inside the curly
braces in f-string and the evaluated result will be printed.
1 CAT1 = 45
2 CAT2 = 40
3 Quiz1 = 8
4 Quiz2 = 7
5 DA = 9
6

7 print ( f " Ram 's internal mark is : { CAT1 *15/50 + CAT2


*15/50 + Quiz1 + Quiz2 + DA } out of 60 ")

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


f-strings in Python 14

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

▶ replace() – method replaces a string/character with another


string/character
1 s = " Hello World !"
2 print ( s . replace ("H" , "J")) # Prints " Jello World !"
3 print ( s . replace (" Hello " , " Hai ")) # Prints " Hai World
!"

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


String Methods 16

▶ 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
! ']"

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


String Methods 17

▶ To check if a certain character of phrase is present in a string or not, we can


use the keywords in or not in.
1 txt = " There is a Rainbow in the Sky "
2 x = " ain " in txt
3 print ( x ) # Prints " True "
4 x1 = " rain " in txt
5 x2 = " Rain " in txt
6 x = " ain " not in txt
7 print ( x ) # Prints " False "

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


String Methods 18

▶ 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

1 s = " hello World !"


2 s1 = s . lower ()
3 print ( s1 ) # prints " hello world !"
4 s2 = s . upper ()
5 print ( s2 ) # prints " HELLO WORLD !"
6 s3 = s2 . capitalize ()
7 print ( s3 ) # prints " Hello world !"
8 s4 = s1 . title ()
9 print ( s4 ) # prints " Hello World !"
10 s5 = s4 . swapcase ()
11 print ( s5 ) # prints " hELLO wORLD !"

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


String Methods 20

▶ islower() – Returns true if the string is in lower case


▶ isupper() – Returns true if the string is in upper case
▶ istitle() – Returns true if the string is in title case
▶ rstrip() – Return the right trim version of the string
▶ lstrip() – Return the left trim version of the string

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


String Methods 21

▶ count() – Returns the number of times a specified value occurs in string


▶ find() – Searches for the specified for the string in the given string and
returns the first position where it is found.
▶ isalnum() – Checks whether the string is alpha numeric
▶ isalpha() – Checks if all the characters in the string are alphabets
▶ isdigit() – Checks if all the characters in the string are digits

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Collections (Arrays) 22

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

4 print ( myList [1]) # Prints the second element in the list


. Index in Python starts from 0
5

6 print ( myList [ -1]) # Print the last element in the list .


-1 refers to last element . -2 refers to second last
element etc .
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Python Lists 24

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

4 print ( myFruits [:4]) # Prints all the elements from


starting first element to upto 4 th element
5

6 print ( myFruits [3:]) # Prints all the elements from


starting with thrid index to last

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Lists 25

1 print ( myFruits [ -4: -1]) # Prints the element from index


-4 ( included ) to index -1 ( excluded )
2

3 myFruits [1] = " grape " # Changes the entry in the index
1
4 print ( myFruits )
5

6 " apple " in myFruits # Returns True if the apple is


present in myFruits list otherwise returns False

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Lists 26

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

A tuple is a collection which is ordered and unchangeable or immutable. In


Python tuples are written with round brackets.
1 myFruits = ( " apple " , " banana " , " cherry ")
2 print ( myFruits )

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Tuples 28

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 )

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Tuples 29

Create Tuple With One Item


To create a tuple with only one item, you have add a comma after the item, unless
Python will not recognize the variable as a tuple.
1 myTuple = ( " apple " ,)
2 print ( type ( myTuple ))
3

4 # NOT a tuple
5 mytuple = ( " apple ")
6 print ( type ( mytuple ))

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Tuples 30

Remove Items from Tuple


One cannot remove items from a Tuple as Tuples are unchangeable. But we can
delete completely the Tuple. using the del command.
1 myFruits = ( " apple " , " banana " , " cherry ")
2 del myFruits
3 print ( myFruits ) # this will raise an error because the
tuple no longer exists

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Tuples 31

Few more commands...


▶ Join two Tuples
1 tuple1 = ( ' First ',' Second ',' Third ')
2 tuple2 = ( ' Fourth ',' Fifth ',' Sixith ')
3 tuple3 = tuple1 + tuple2
4 print ( tuple3 )
▶ To know the number of times an element appears in a Tuple
[Link]('element')
▶ To know the index of a particular entry in a Tuple [Link]('Fourth')

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Tuples 32

Few more commands...


▶ Repeat the elements of a tuple
1 tuple1 = ( ' First ',' Second ',' Third ')
2 tuple2 = tuple1 * 3
3 print ( tuple2 ) # Prints the tuple1 3 times

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Sets 33

▶ Sets are unordered collection of objects.


▶ In Python sets are written with curly brackets.
▶ We can also creates sets using the set() constructor by passing list of
elements.
▶ Sets are unordered, so you cannot be sure in which order the items will
appear.
▶ You cannot access items in a set by referring to an index, since sets are
unordered the items has no index.
▶ But we can loop through the elements of a set using for and membership
function in

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Sets 34

1 myfruits = { " apple " , " banana " , " cherry "}
2 print ( myfruits )
3

4 for x in myfruits :
5 print ( x )
6

7 print ( " banana " in myfruits )


8

9 print ( " orange " in my fruits )

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Sets 35

▶ To add an element(s) we can use add('item') or update(['items'])


commands.
▶ To remove an element we can use either remove('item') or
discard('item')
▶ remove() returns an error if the element does not exist in the Set.
▶ discard() does not return an error.
▶ We can also use pop() method. But as Sets are unordered, we will not know
which element gets removed by using pop() command.

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Sets 36

1 myfruits = { " apple " , " banana " , " cherry "}
2 myfruits . add ( " orange ")
3 print ( myfruits )
4

5 myfruits . update ([ " orange " , " mango " , " grapes " ])
6 print ( myfruits )
7

8 print ( len ( myfruits )) # Prints the no . of elements in the


set
9

10 myfruits . remove (" banana ")


11 print ( myfruits )
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Python Sets 37

1 myfruits . discard (" banana ")


2 print ( myfruits )
3

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

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Sets 39

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

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Sets 40

1 set1 = {"x" ,"y" ,"z"}


2 set2 = {1 ,2 ,3 ,4 ,5}
3

4 set3 = set1 . union ( set2 ) # union of set1 and set2


5 print ( set3 )
6

7 set4 = {"x" ,"z" ,4 ,2 ,7 ,10}


8 set5 = set4 . intersection ( set1 ) # intersection of set4 , set1
9 set6 = set4 . intersection ( set2 ) # intersection of set4 , set2
10

11 print ( set5 )
12 print ( set6 )
13

14 set1 . update ( set2 ) # adds the elements of set2 to set1


Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Python Dictionaries 41

▶ A dictionary is a collection which is ordered2 , changeable and indexed.


▶ A dictionary is represented by a pair of curly braces {} in which enclosed are
the “key: value” pairs separated by a comma.
▶ Python dictionary keys are immutable (which cannot be changed) data types
that can be either strings or numbers.
▶ However, a key can not be a mutable data type, for example, a list.
▶ Keys are unique within a dictionary and can not be duplicated inside a
dictionary.
▶ Key connects with the value, hence, creating a map-like structure.
2
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are
unordered
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Python Dictionaries 42

1 myDict = {
2 " brand " : " HP " ,
3 " btype " : " Convertible " ,
4 " byear " : 2019
5 }
6 print ( myDict )

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Dictionaries 43

We can use the dict() constructor also to make a new dictionary:


1 myDict = dict ( brand =" HP " , btype =" Convertible " , byear
=2019)
2 # Please note that the keywords string literals with
out quotes
3 # We are using '=' in dict () constructor instead of
colon (:) for assignment
4 print ( myDict )

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Dictionaries
Unique Keys 44

The keys in a dictionary have to be unique:


1 dictionary_unique = {"a": " Alpha " , "b": " Beta " , "g": "
Gamma " }
2 print ( dictionary_unique )
3

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

4 print ( myDict . items () )


To access the keys of a dictionary:
1 print ( myDict . keys () )
To access the values of a dictionary:
1 print ( myDict . values () )
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Python Dictionaries 46

we could even access a value by specifying a key as a parameter to the dictionary.


To access the items of a dictionary we can either
▶ refer to its key name, inside square brackets
▶ we can use the get() method

1 x = myDict [ " type "]


2 print ( x )
3 x = myDict . get (" type ")
4 print ( x )

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Dictionaries 47

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 )

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Dictionaries
Removing Items 48

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 )

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Dictionaries
Removing Items 49

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 )

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Dictionaries
Removing Items 50

The del keyword deletes the complete dictionary


1 del myDict
2 print ( myDict )
clear() function empties the dictionary:
1 myDict = {
2 " brand " : " Lenovo " ,
3 " btype " : " Tablet " ,
4 " byear " : 2019
5 }
6 print ( myDict )
7 myDict . clear ()
8 print ( myDict )
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Python Dictionaries
Removing Items 51

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 )

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Dictionaries
Nested Dictionaries 52

We can even create nested dictionaries


1 myDict = {
2 " prod1 " : {
3 " bname " : " HP " ,
4 " btype ": " Computer " ,
5 " byear " : 2019
6 },
7 " prod2 " : {
8 " bname " : " Lenovo " ,
9 " btype " : " Tablet " ,
10 " byear " :2019
11 },
12 " prod3 " : {
13 " bname ": " Microsoft " ,
14 " btype " : " Convertible " ,
15 " byear ": 2020
16 }
17 }
18 print ( myDict )
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Python Dictionaries
Nested Dictionaries 53

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

Accessing the elements of a nested dictionary:


1 print ( myDict [ " prod1 " ])
2 # Output : { ' bname ': 'HP ', ' btype ': ' Computer ', ' byear ':
2019}
3

4 myDict [ " prod1 " ][ " bname "]


5 # Output : ' HP '
6

7 myDict [ " prod3 " ][ " btype "]


8 # Output : ' Convertible '

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Dictionaries
Looping through dictionaries 55

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

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python For Loop and Dictionary
Word Frequency 56

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

Consider the following Mathematical Lists:

S = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81};

V = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096};
M = {0, 4, 16, 36, 64}

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Loop Version 58

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

▶ List comprehension is an important techniques using which we can create a


list of numbers and dictionaries easily.
▶ List comprehension in Python is surrounded by brackets, but instead of the
list of data inside it, you enter an expression followed by for loop and
if-else clauses.
▶ A most basic form of List comprehension in Python is constructed as follows:
list_variable = [expression for item in collection]
▶ The above expression generates elements in the list followed by a for loop
over some collection of data which would evaluate the expression for every
item in the collection.

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Conditional List Comprehension 60

List Comprehension with an if condition:


1 listcomp = [ expression for item in iterable if
condition == True ]
The above code is equivalent to the following for loop:
1 listcomp =[]
2 for item in iterable :
3 if condition == True :
4 listcomp . append ( expression )

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Conditional List Comprehension 61

List Comprehension with an if. . . else condition:


1 listcomp = [ expression1 if condition == True else
expression2 for item in iterable ]
The above code is equivalent to the following for loop:
1 listcomp =[]
2 for item in iterable :
3 if condition == True :
4 listcomp . append ( expression1 )
5 else :
6 listcomp . append ( expression2 )

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


List Comprehension Version 62

The Python code with List Comprehension technique is:


1 S = [x **2 for x in range (10) ]
2 # Output : S = [0 , 1, 4, 9, 16 , 25 , 36 , 49 , 64 , 81]
3 V = [2** i for i in range (13) ]
4 # Output : V = [1 , 2, 4, 8, 16 , 32 , 64 , 128 , 256 , 512 ,
1024 , 2048 , 4096]
5 M = [x for x in S if x % 2 == 0]
6 # Output M = [0 , 4, 16 , 36 , 64]
7 M1 = [ x if x %2 == 0 else x /2 for x in S]
8 # Output M1 = [0 , 0.5 , 4, 4.5 , 16 , 12.5 , 36 , 24.5 , 64 ,
40.5]

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Advantages of List Comprehension 63

▶ Time-efficient and space-efficient than loops.


▶ Require fewer lines of code.
▶ Transforms iterative statement into a formula.

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Nested List Comprehension 64

Consider the example of preparing a matrix


 
1 2 3 4
5 6 7 8
M= 
 9 10 11 12
13 14 15 16

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Nested List Comprehension 64

Consider the example of preparing a matrix


 
1 2 3 4
5 6 7 8
M= 
 9 10 11 12
13 14 15 16

the Python code using the for loop is:


1 M = []
2 for i in range (4) :
3 M . append ([])
4 for j in range (1 ,5) :
5 M[ i ]. append (4* i+ j)
6 print ( M )
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Nested List Comprehension 64

Consider the example of preparing a matrix


 
1 2 3 4
5 6 7 8
M= 
 9 10 11 12
13 14 15 16

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

1 set_comprehension = {i **3 for i in range (10) }


2

3 print ( set_comprehension )
4

5 for value in set_comprehension :


6 print ( value , end =" ")

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Dictionary Comprehension 66

1 dict_comprehension = {i: i **3 for i in range (10) }


2

3 for key , value in dict_comprehension . items () :


4 print ( key , value )

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming

You might also like