[Go to site: main page, start]

0% found this document useful (0 votes)
8 views44 pages

Python Lists and Dictionaries Basics

Module 2 of the Introduction to Python Programming course covers lists, dictionaries, and string manipulation. It explains the list data type, how to access and modify list elements, and introduces augmented assignment operators. Additionally, it includes practical projects and examples to illustrate the concepts discussed.

Uploaded by

ARUN KUMAR P
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)
8 views44 pages

Python Lists and Dictionaries Basics

Module 2 of the Introduction to Python Programming course covers lists, dictionaries, and string manipulation. It explains the list data type, how to access and modify list elements, and introduces augmented assignment operators. Additionally, it includes practical projects and examples to illustrate the concepts discussed.

Uploaded by

ARUN KUMAR P
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

Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

Module 2

Lists, Dictionaries and Structuring Data, Manipulating Strings

Lists: The List Data Type, Working with Lists, Augmented Assignment Operators, Methods,
Example Program: Magic 8 Ball with a List, List-like Types: Strings and Tuples, References.
Dictionaries and Structuring Data: The Dictionary Data Type, Pretty Printing, Using Data
Structures to Model Real-World Things
Manipulating Strings: Working with Strings, Useful String Methods, Project: Password
Locker, Project: Adding Bullets to Wiki Markup

.IN
Textbook 1: Chapters 4 – 6 RBT: L1, L2, L3

C
Textbook 1: Al Sweigart, “Automate the Boring Stuff with Python”, 1 st Edition, No Starch Press,
N
2015. (Available under CC-BY-NC-SA license at [Link]
SY

2.1. The List Data Type


• A list can be defined as a collection of values or items of same or different types.
U

• The items in the list are separated with the comma (,) and enclosed with the square brackets [].
• A list is a value that contains multiple values in an ordered sequence.
VT

• A list is mutable (new, deleted, modify).


• The values in list are called elements or sometimes items.
• The value [] is an empty list that contains no values, similar to '', the empty string.
• A list can be defined as follows.
L1 = ["Raju", 102, "India"] #Creates list ['Raju', 102, 'India']
L2 = [1, 2, 3, 4, 5, 6] #Creates List [1, 2, 3, 4, 5, 6]
L3 = [ ] #Creates List L3 with no items
spam = ['cat', 'bat', 'rat', 'elephant']

 A list can be displayed as follows.


print(L1) #displays ['Raju', 102, 'India']
print(L2) #displays [1, 2, 3, 4, 5, 6]

Department of CSE, EPCET Page 1 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

print(L3) #displays [ ]
print(spam) #displays ['cat', 'bat', 'rat', 'elephant']

Getting Individual Values in a List with Indexes


• To access values in lists, use the square brackets for slicing along with the index or indices to
obtain value available at that index.
• The integer inside the square brackets that follows the list is called an index.
• The first value in the list is at index 0, the second value is at index 1, the third value is at index 2,
and so on.

>>> spam = ['cat', 'bat', 'rat', 'elephant']

.IN
>>> spam #['cat', 'bat', 'rat', 'elephant']
>>> spam[0] #'cat'
>>> spam[1]
>>> spam[2]
#'bat'
#'rat'
C
N
>>> spam[3] #'elephant‘
SY

>>> spam[1.0] #TypeError: list indices must be integers


>>> spam[int(1.0)] #’bat’
>>> spam[4] #IndexError: list index out of range
U

>>> 'Hello ' + spam[2] #'Hello rat‘


VT

>>> 'The ' + spam[0] + ' ate ' + spam[2] #'The cat ate rat'

• Lists can also contain other list values. The values in these lists of lists can be accessed using
multiple indexes.
• The first index dictates which list value to use, and the second indicates the value within the list
value.
>>> spam = [['cat', 'bat'], [10, 20, 30, 40, 50]]
>>> spam #[['cat', 'bat'], [10, 20, 30, 40, 50]]
>>> spam[0][1] #'bat'
>>> spam[1][4] #50
>>> spam[2][0] #IndexError: list index out of range
>>> spam[1][5] #Index Error

Department of CSE, EPCET Page 2 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

Negative Indexes
• Indexes start at 0 and go up, we can also use negative integers for the index.
• The integer value -1 refers to the last index in a list, the value -2 refers to the second-to-last index in
a list, and so on.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1] #'elephant'
>>> spam[-3] #'bat'
>>> spam[3] #elephant
• Indexes start at 0 and go up, we can also use negative integers for the index.
• The integer value -1 refers to the last index in a list, the value -2 refers to the
second-to-last index in a list, and so on.

.IN
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1] #'elephant'
>>> spam[-3] #'bat'
C
>>> 'The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.‘
N
#'The elephant is afraid of the bat.'
SY

Getting Sublists with Slices


• An index can get a single value from a list, A slice can get several values from a list in the form of a
U

new list.

VT

A slice is typed between square brackets like an index but it has 2 integers separated by a colon.
• The difference between indexes and slices.
o spam[2] is a list with an index (one integer).
o spam[1:4] is a list with a slice (two integers).
o In a slice, the first integer is the index where the slice starts (including) and second integer is
the index where the slice ends (Excluding) and evaluates to a new list value

>>> spam = ['cat', 'bat', 'rat', 'elephant']


>>> spam[0:4] #['cat', 'bat', 'rat', 'elephant']
>>> spam[1:3] #['bat', 'rat']
>>> spam[0:-1] #['cat', 'bat', 'rat']
>>> spam[::-1] #['elephant', 'rat', 'bat', 'cat']

Department of CSE, EPCET Page 3 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

 We can leave out one or both of the indexes on either side of the colon in the slice.
 Leaving out the first index is the same as using 0 and Leaving out the second index is same as
using the length of the list.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[:2] #['cat', 'bat'] prints elements of pos 0 and 1
>>> spam[1:] #['bat', 'rat', 'elephant'] prints all excluding 0
>>> spam[:] #['cat', 'bat', 'rat', 'elephant'] prints all

Getting a List’s Length with len()


 The len() function will return the number of values that are in a list value passed to it, just like it

.IN
can count the number of characters in a string value.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> len(spam)

C
N
Changing Values in a List with Indexes
 When the bracket operator appears on the left side of an assignment, it identifies the element of
SY

the list that will be assigned.


>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[1] = 'aardvark‘ #pos 1 bat value is changed to aardvark
U

>>> spam #['cat', 'aardvark', 'rat', 'elephant']


VT

>>> spam[2]=spam[1] # pos 1 value is assigned to pos 2


>>> spam #['cat', 'aardvark', 'aardvark', 'elephant']
>>> spam[-1] = 12345 #last pos vaue is changed to 12345
>>> spam #['cat', 'aardvark', 'aardvark', 12345]

 The + operator can combine two lists to create a new list value in the same way it combines two
strings into a new string value.
 The * operator can also be used with a list and an integer value to replicate the list.
>>> [1, 2, 3] + ['A', 'B', 'C'] #[1, 2, 3, 'A', 'B', 'C']
>>> ['X', 'Y', 'Z'] * 3 #['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
>>> spam = [1, 2, 3]
>>> spam = spam + ['A', 'B', 'C']
>>> spam #[1, 2, 3, 'A', 'B', 'C']

Department of CSE, EPCET Page 4 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

 The del statement will delete values at an index in a list.


 All of the values in the list after the deleted value will be moved up one index.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> del spam[2] #deletes element at pos 2
>>> spam #['cat', 'bat', 'elephant']
>>> del spam[2] #deletes element at pos 2
>>> spam #['cat', 'bat']

Insertion of elements into LIST


 append: [Link](10) #insert ele at last pos

.IN
insert: [Link](1,23) #insert 23 in pos 1
 [Link](-1,20) #insert 20 into lastpos-1
 If index is not available to insert, item will be inserted at last pos

C
N
Removing Values from Lists with del Statements
The del statement can also be used on a simple variable to delete it, as if it were an “unassignment”
SY

statement.
If you try to use the variable after deleting it, you will get a NameError error because the variable no
longer exists.
U

>>> del spam #deletes all elements in spam list


VT

>>> spam #NameError: name 'spam' is not defined

2.2. Working with Lists


 Advantages of using lists : lists program will become much more flexible in processing data than
it would be with several repetitive variables.
catnames = []
while True:
print('Enter name of cat'+str(len(catnames)+1) + 'or q to stop')
name = input()
if name == 'q' :
break
catnames = catnames + [name] # list concatenation

Department of CSE, EPCET Page 5 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

print('The cat names are:')


for name in catnames:
print(name)

Output:
Enter name of cat1or q to stop: candy
The cat names are: candy
Enter name of cat2or q to stop: arjun
The cat names are: candy arjun
Enter name of cat3or q to stop: q

.IN
Using for Loops with Lists
 A for loop repeats the code block once for each value in a list or list-like value.
for i in range(4):
print(i)
C # accepts 0 to 4
#outputs 01234
N
is same as
SY

for i in [0, 1, 2, 3]:


print(i) #outputs 01234
U

supplies = ['pens', 'staplers', 'flame-throwers', 'binders']


VT

for i in range(len(supplies)): # 0 to 3
print('Index ' + str(i) + ' in supplies is: ' + supplies[i])

Output: Index 0 in supplies is: pens


Index 1 in supplies is: staplers
Index 2 in supplies is: flame-throwers
Index 3 in supplies is: binders

The in and not in Operators


in and not in are used in expressions and connect two values: a value to look for in a list and the list
where it may be found.
To determine whether a value is or isn’t in a list by using in and not in operators.

Department of CSE, EPCET Page 6 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

These expressions will evaluate to a Boolean value


>>> 'hello' in ['hello', 'hi', 'how', 'are','you'] #True
>>> spam=['hello', 'hi', 'how', 'are','you']
>>> 'cat' in spam #False
>>> 'howdy' not in spam #True
>>> 'cat' not in spam #True
>>> 'how' not in spam #False

myFruits = ['Apple', 'Orange', 'Banana']


print('Enter a Fruit name:')
name = input() #read name from user

.IN
if name not in myFruits:
print('I do not have a Fruit named ' + name + ' in my List')
else:
print(name + ' is in my Fruit List.')
C
N
SY

The Multiple Assignment Trick


 The multiple assignment trick is a shortcut that allows us to assign multiple variables with the
values in a list in one line of code
U

Normal Way
VT

>>> cat = ['fat', 'black', 'loud']


>>> size = cat[0]
>>> color = cat[1]
>>> color = cat[1]
>>> disposition = cat[2]
>>> size #'fat'
>>> color #'black'
>>> disposition #'loud'
>>> cat = ['fat', 'black', 'loud']
>>> size, color, disposition= cat
>>> size,color,disposition #('fat', 'black', 'loud')

Department of CSE, EPCET Page 7 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

 The number of variables and the length of the list must be exactly equal, or Python will give you
a ValueError:
>>> size, color, disposition, name = cat
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
size, color, disposition, name = cat
ValueError: not enough values to unpack (expected 4, got 3)

2.3. Augmented Assignment Operators


 When assigning a value to a variable, you will frequently use the variable itself.
>>> spam = 42

.IN
>>> spam = spam + 1
>>> spam #43

C
As a shortcut, you can use the augmented assignment operator += to do the same thing:
>>> spam = 42
N
>>> spam += 1 #spam = spam + 1
SY

>>> spam #43


U
VT

 The += operator can also do string and list concatenation, and the *= operator can do string and
list replication.
>>> fruits='Apple'
>>> fruits+=' Banana'
>>> fruits+=' Mango'
>>> fruits #'Apple Banana Mango‘

Department of CSE, EPCET Page 8 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

>>> fruits=['Apple']
>>> fruits *=3 #fruits*3
>>> fruits #['Apple', 'Apple', 'Apple']

2.4. Methods
Methods: Finding a Value in a List with the index() Method
 A method is the same thing as a function, except it is “called on” a value.
 Each data type has its own set of methods.
 List values have an index() method that can be passed a value, and if that value exists in the list,
the index of the value is returned. If the value isn’t in the list, then Python produces a ValueError

.IN
error.
>>> spam = ['hello', 'hi', 'how', 'are','you']
>>> [Link]('hello') #0
>>> [Link]('how')
>>> [Link]('hello hi')
C #2
#'hello hi' is not in list
N
 When there are duplicates of the value in the list, the index of its first appearance is returned.
SY

>>> spam = ['hello', 'hi', 'how', 'are','hello','you']


>>> [Link]('hello') #0
U

Adding Values to Lists with the append() and insert() Methods


VT

 To add new values to a list, use the append() and insert() methods.
 The append() method call adds the argument to the end of the list.
 The insert() method can insert a value at any index in the list.
>>> fruits=['Apple','Mango','Orange']
>>> fruits # ['Apple', 'Mango', 'Orange']
>>> [Link]('Grapes')
>>> fruits #['Apple', 'Mango', 'Orange', 'Grapes']
>>> fruits=['Apple','Mango','Orange']
>>> fruits # ['Apple', 'Mango', 'Orange']
>>> [Link](1,'Grapes')
>>> fruits #['Apple', 'Grapes', 'Mango', 'Orange']

Department of CSE, EPCET Page 9 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

 The append() and insert() methods are list methods and can be called only on list values, not on
other values such as strings or integers.

append() and insert() on List


>>> fruits=['Apple']
>>> fruits #['Apple']
>>> [Link]('Mango')
>>> fruits #['Apple', 'Mango']

append() and insert() on String


>>> fruits='Apple'

.IN
>>> [Link]('Mango') #AttributeError: ‘int' object has no
attribute 'append'

append() and insert() on integer


C
N
>>> num=42
SY

>>> [Link](1,23) #AttributeError: ‘int' object has no attribute 'append'

Removing Values from Lists with remove()


U

 The remove() method is passed the value to be removed from the list it is called on.
VT

>>> fruits=['Apple', 'Grapes', 'Mango', 'Orange']


>>> [Link]('Mango')
>>> fruits #['Apple', 'Grapes', 'Orange']

 Attempting to delete a value that does not exist in the list will result in a ValueError error.
>>> fruits=['Apple', 'Grapes', 'Mango', 'Orange']
>>> [Link]('Pineapple') #ValueError: [Link](x): x not in list

 If the value appears multiple times in the list, only the first instance of the value will be removed.
>>> fruits=['Apple', 'Grapes','Apple', 'Grapes', 'Mango', 'Orange']
>>> fruits #['Apple', 'Grapes', 'Apple', 'Grapes', 'Mango', 'Orange']
>>> [Link]('Grapes')

Department of CSE, EPCET Page 10 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

>>> fruits #['Apple', 'Apple', 'Grapes', 'Mango', 'Orange']


 The del statement is good to use when you know the index of the value you want to remove from
the list. The remove() method is good when you know the value you want to remove from the list.

Sorting the Values in a List with the sort() Method


 Lists of number values or lists of strings can be sorted with the sort() method.
>>> spam = [2, 5, 3.14, 1, -7]
>>> [Link]()
>>> spam #[-7, 1, 2, 3.14, 5]
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> spam #['ants', 'cats', 'dogs', 'badgers', 'elephants']

.IN
>>> [Link]()
>>> spam #['ants', 'badgers', 'cats', 'dogs', 'elephants']

C
To sort the values in reverse order, pass True for the reverse keyword argument to have sort()
function
N
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
SY

>>> [Link](reverse=True)
>>> spam #['elephants', 'dogs', 'cats', 'badgers', 'ants']
U

 sort() function cannot sort lists that have both number values and string values in them, since
VT

Python doesn’t know how to compare these values.


>>> spam = [1, 3, 2, 4, 'Alice', 'Bob']
>>> [Link]() #TypeError: '<' not supported between instances of 'str' and 'int'
sort() uses “ASCIIbetical order” rather than actual alphabetical order for sorting
strings. This means uppercase letters come before lowercase letters. Therefore,
the lowercase a is sorted so that it comes after the uppercase Z.

>>> spam = ['Alice', 'ants', 'Bob', 'badgers', 'Carol', 'cats']


>>> [Link]()
>>> spam #['Alice', 'Bob', 'Carol', 'ants', 'badgers', 'cats']

Department of CSE, EPCET Page 11 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

 If you need to sort the values in regular alphabetical order, pass str. lower for the key keyword
argument in the sort() method call.
>>> spam = ['a', 'z', 'A', 'Z']
>>> [Link](key=[Link])
>>> spam #['a', 'A', 'z', 'Z']

2.5. Example Program: Magic 8 Ball


 Using lists, you can write a much more elegant version of the Magic 8 Ball program. Instead of
several lines of nearly identical elif statements, you can create a single list that the code works
with.
 Open a new file editor window and enter the following code.

.IN
import random
messages = ['It is certain',
'It is decidedly so',
'Yes definitely', C
N
'Reply hazy try again',
SY

'Ask again later',


'Concentrate and ask again',
'My reply is no',
U

'Outlook not so good',


VT

'Very doubtful']
print(messages[[Link](0, len(messages) - 1)]) #Output: Very doubtful

 When you run this program, you’ll see that it works the same as the previous [Link]
program.
 Notice the expression you use as the index into messages: [Link](0, len(messages) - 1).
 This produces a random number to use for the index, regardless of the size of messages. That is,
you’ll get a random number between 0 and the value of len(messages) - 1.
 The benefit of this approach is that you can easily add and remove strings to the messages list
without changing other lines of code.
 If you later update your code, there will be fewer lines you have to change and fewer chances for
you to introduce bugs.

Department of CSE, EPCET Page 12 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

2.6. List-like Types: Strings and Tuples


 Lists aren’t the only data types that represent ordered sequences of values. For example, strings
and lists are actually similar, if you consider a string to be a “list” of single text characters.
 Many of the things you can do with lists can also be done with strings: indexing; slicing; and using
them with for loops, with len(), and with the in and not in operators.
 Example
import random
messages = ['It is certain', 'It is decidedly so', 'Yes definitely',
'Reply hazy try again', 'Ask again later', 'Concentrate and ask again',
'My reply is no', 'Outlook not so good', 'Very doubtful']
print(messages[[Link](0, len(messages) - 1)])

.IN
 Output
Very doubtful
Concentrate and ask again C
N
My reply is no
SY

 Example
>>> name='Apple‘
>>> name[0] #'A'
U

>>> name[-2] #'l'


VT

>>> name[0:4] #'Appl'


>>> 'Ap' in name #True
>>> 'p' not in name #False
>>> for i in name:
print('* * *' + i + '* * *')
 Output
* * *A* * *
* * *p* * *
* * *p* * *
* * *l* * *
* * *e* * *

Department of CSE, EPCET Page 13 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

Mutable and Immutable Data Types


 A list value is a mutable data type: It can have values added, removed, or changed. However, a
string is immutable: It cannot be changed. Trying to reassign a single character in a string
results in a TypeError error.
>>> name='Hello how are you?‘
>>> name[2]='P‘ #TypeError: 'str' object does not support item assignment
 The proper way to “mutate” a string is to use slicing and concatenation to build a new string by
copying from parts of the old string.
>>> name="Apple is the fruit“
>>> name #'Apple is the fruit‘
>>> new_name=name[0:8] + ' a ' + name[13:18]

.IN
>>> new_name #'Apple is a fruit'

List is Mutable
>>> eggs=[1,2,3]
C
N
>>> eggs #[1, 2, 3]
SY

>>> eggs=[4,5,6]
>>> eggs #[4, 5, 6]
 The list value in eggs isn’t being changed here; rather, an entirely new and different list value ([4,
U

5, 6]) is overwriting the old list value ([1, 2, 3]).


VT

Mutable and Immutable Data Types


If you wanted to actually modify the original list, then
>>> eggs = [1, 2, 3]
>>> eggs #[1, 2, 3]
>>> eggs[0]=5 #Modify position 0 value to 5
>>> eggs #[5, 2, 3]
>>> del eggs[2] #delete a value from position 2
>>> eggs #[5, 2]
>>> [Link](6) #insert value 6 to end of list
>>> eggs #[5, 2, 6]

Department of CSE, EPCET Page 14 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

The Tuple Data Type


 The tuple data type is almost identical to the list data type, except in two ways. First, Tuples are
typed with parentheses, ( and ), instead of square brackets, [ and ].
 Second, Tuples are immutable (cannot have their values modified, appended, or removed).
>>> eggs=('Apple', 1, 2, 3)
>>> eggs #('Apple', 1, 2, 3)
>>> type(eggs) #<class 'tuple'>
>>> eggs[0]=0
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
eggs[0]=0

.IN
TypeError: 'tuple' object does not support item assignment
If you have only one value in your tuple, you can indicate this by placing a trailing comma after the

C
value inside the parentheses. Otherwise, Python will treat as normal data type values.
N
>>> eggs1=(2)
SY

>>> eggs1 #2
>>> type(eggs1) #<class 'int'>
>>> type(('hello')) #<class 'str'>
U
VT

>>> eggs2=(2,)
>>> eggs2 #(2,)
>>> type(eggs2) #<class 'tuple'>
>>> type(('hello',)) #<class 'tuple'>

Converting Types with the list() and tuple() Functions


>>> list1=[1,2,3,4]
>>> tup1=tuple(list1) #converts list to tuple
>>> tup1 #(1, 2, 3, 4)
>>> list(('cat', 'dog', 5)) #['cat', 'dog', 5]
>>> list2=list(('cat', 'dog', 5))
>>> list2 #['cat', 'dog', 5]

Department of CSE, EPCET Page 15 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

>>> list3=list('hello')
>>> list3 #['h', 'e', 'l', 'l', 'o']

2.7. References
 Variables store strings and integer values
>>> spam=42
>>> cheese=spam
>>> spam=100
>>> spam #100
>>> cheese #42
 When you assign a list to a variable, you are actually assigning a list reference to the variable. A

.IN
reference is a value that points to some bit of data, and a list reference is a value that points to a
list.
>>> spam = [0, 1, 2, 3, 4, 5]
>>> cheese = spam
C
N
>>> cheese[1] = 'Hello!'
SY

>>> cheese #[0, 'Hello!', 2, 3, 4, 5]


>>> spam #[0, 'Hello!', 2, 3, 4, 5]
U

 When you create the list,


VT

1. Assign a reference to list variable.


2. Copies only the list reference, not the list value itself.
3. Modifying the same list affects reference.

Passing References
References are particularly important for understanding how arguments get passed to functions. When a
function is called, the values of the arguments are copied to the parameter variables.
def eggs(Param):
[Link]('Hello')
spam = [1, 2, 3]
eggs(spam)

Department of CSE, EPCET Page 16 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

print(spam) #[1, 2, 3, 'Hello']

The copy Module’s copy() and deepcopy() Functions


 If the function modifies the list or dictionary that is passed, these changes will affect the original
list or dictionary value.
 For this, Python provides a module named copy that provides both the copy() and deepcopy()
functions. [Link](), can be used to make a duplicate copy of a mutable value like a list or
dictionary, not just a copy of a reference.
>>> import copy
>>> spam = ['A', 'B', 'C', 'D']
>>> cheese=[Link](spam)

.IN
>>> spam #['A', 'B', 'C', 'D']
>>> cheese #['A', 'B', 'C', 'D']
>>> cheese[0]='Z'
>>> cheese
C #['Z', 'B', 'C', 'D']
N
>>> spam #['A', 'B', 'C', 'D']
SY

>>> spam[3]='X‘
>>> spam #['A', 'B', 'C', 'X']
>>> cheese #['Z', 'B', 'C', 'D']
U


VT

If the function modifies the list or dictionary that is passed, these changes will affect the original
list or dictionary value.
 For this, Python provides a module named copy that provides both the copy() and deepcopy()
functions.
 [Link](), can be used to make a duplicate copy of a mutable value like a list or dictionary, not
just a copy of a reference.
 Deep copy is a process in which the copying process occurs recursively. In case of deep copy, a
copy of object is copied in other object.
 Any changes made to a copy of object do not reflect in the original object. In python, this is
implemented using “deepcopy()” function.

Department of CSE, EPCET Page 17 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

The copy Module’s copy() and deepcopy() Functions


# importing copy module
import copy
list1 = [1, 2, [3,5], 4]
list2 = [Link](list1)
list3 = [Link](list1)
print(list1) #[1, 2, [3, 5], 4]
print(list2) #[1, 2, [3, 5], 4]
print(list3) #[1, 2, [3, 5], 4]

2.8. Dictionaries and Structuring Data

.IN
 A dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written
with curly brackets { }, and they have keys and values. Indexes for dictionaries are called keys,


C
and a key with its associated value is called a key-value pair.
The main difference is that List uses index to access the elements. Dictionary uses keys to access
N
the elements. The function “ dict “ creates a new dictionary with no items. dict is the name of a
SY

built-in function, avoid using it as a variable name.


>>> d=dict()
>>> print(d) #{}
U

 Dictionaries can still use integer values as keys, just like lists use integers for indexes, but they
VT

do not have to start at 0 and can be any number.


{51: 'CNS', 52: 'CG', 53: 'DBMS', 54: 'ATC', 55: 'ADP'}

Create and print Dictionary


d={
"brand": "toyota",
"model": "etios liva",
"year": 2011
}

print(d)
or

Department of CSE, EPCET Page 18 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

d = { "brand": "toyota", "model": "etios liva", "year": 2011 }


print(d)

Dictionaries vs. Lists

LIST DICTIONARY

List is a collection of index values pairs as that Dictionary is a hashed structure of key and
of array in c++. value pairs.

Dictionary is created by placing elements in {


List is created by placing elements in [ ]
} as “key”:”value”, each key value pair is
seperated by commas “, “
seperated by commas “, ”

.IN
The indices of list are integers starting from 0. The keys of dictionary can be of any data type.

The elements are accessed via indices. The elements are accessed via key-values.

The order of the elements entered are


C
N
There is no guarantee for maintaining order.
maintained.
SY

 Items in dictionaries are unordered. First element in the list would be at index 0. But, no first
item in dictionary. Dictionaries are not ordered, they can’t be sliced like lists.
U

>>> spam = ['cats', 'dogs', 'moose']


>>> bacon = ['dogs', 'moose', 'cats']
VT

>>> spam == bacon #False


>>> eggs = {'name': 'Zophie', 'species': 'cat', 'age': '8'}
>>> ham = {'species': 'cat', 'age': '8', 'name': 'Zophie'}
>>> eggs == ham
 Though dictionaries are not ordered, the fact that you can have arbitrary values for the keys allows
you to organize your data in powerful ways. Example: program to store data about birthdays using
a dictionary with the names as keys and the birthdays as values.

birthdays = {'Raju': 'Apr 19', 'Manu': 'Jul 12', 'Anup': 'Jul 9'}
while True:
print('Enter a name: (blank to quit)')
name = input()

Department of CSE, EPCET Page 19 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

if name == '':
break

if name in birthdays:
print(birthdays[name] + ' is the birthday of ' + name)
else:
print('I do not have birthday information for ' + name)
print('What is their birthday?')
bday = input()
birthdays[name] = bday
print('Birthday database updated.')

.IN
The keys(), values(), and items() Methods

C
There are three dictionary methods that will return dictionary’s keys, values, or both keys and
values: keys(), values(), and items().
N
 The values returned by these methods are not true lists: They cannot be modified and do not have
SY

an append() method.
 But these data types (dict_keys, dict_values, and dict_items, respectively) can be used in for loops.
 A for loop iterates over each of the values in the spam dictionary
U

 Example
VT

spam = {'color': 'red', 'age': 42}


for v in [Link]():
print(v) #red 42
for v in [Link]():
print(v) #color age

 A for loop can also iterate over the keys or both keys and values:
spam = {'color': 'red', 'age': 42}
for k in [Link]():
print(spam[k]) # red 42
for i in [Link]():
print(i) #('color', 'red') ('age', 42)

Department of CSE, EPCET Page 20 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

 Using the keys(), values(), and items() methods, a for loop can iterate over the keys, values, or
key-value pairs in a dictionary. The values in the dict_items value returned by the items() method
are tuples of the key and value.
spam = {'color': 'red', 'age': 42}
for k in [Link]():
print(spam[k]) # red 42
for i in [Link]():
print(i) #('color', 'red') ('age', 42)
 The get() method returns the value of the item with the specified key.
Syntax: [Link](keyname, value)
Parameter Values

.IN
Keyname Required The keyname of the item you want to return the value from
value  Optional  A value to return if the specified key does not exist. Default value
None
C
N
The get() Method
SY

 Items in the dictionary can be accessed by referring to its key name, inside square brackets. Get
the value of the "model" key:
>>> d = { "brand": "toyota", "model": "etios liva", "year": 2011 }
U

>>> x = d["model“] here, model is key


VT

>>> print(x) #etios liva


 There is also a method called get() that will give you the same result:
 Get the value of the "model" key:
>>> x = [Link]("model")
car = { "brand": "toyota", "model": "etios liva", "year": 2011 }
y=[Link]("year") #2011
c=[Link]("color") #nothing
c1=[Link]("color”,2020) #2020
print(y) #2011
print(c) #None
print(c1) #2020
print(car) #{'brand': 'toyota', 'model': 'etios liva', 'year': 2011}

Department of CSE, EPCET Page 21 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

>>> car={'brand': 'toyota', 'model': 'etios liva', 'year': 2011}


>>> 'I bought '+str([Link]('brand',0)) + ' car ' +str([Link]('model',0)) + ' model ' + 'in the year '
+ str([Link]('year‘,2000))

Output: 'I bought toyota car etios liva model in the year 2011‘

 If no key in the dictionary, the default value 0 is returned by the get() method. If no get method is
used and no key present in dictionary, then ERROR will be raised.
>>> car={'brand': 'toyota', 'model': 'etios liva', 'year': 2011}
>>> I bought '+str(car['brand']) + ' color: ' + str(car['color'])
Output: KeyError: 'color'

.IN
The setdefault() Method

C
To set a value in a dictionary for a certain key only if that key does not already have a value, then
setdefault() method is used.
N
SY

General Way
fruits = {'name': 'Apple', 'cost': 90}
if 'color' not in fruits:
U

fruits['color'] = 'green'
VT

print(fruits)

Using setdeault
fruits = {'name': 'Apple', 'cost': 90}
[Link]('color', 'black')
print(fruits)

Output:{'name': 'Apple', 'cost': 90, 'color': 'black'}

Using setdeault
fruits = {'name': 'Apple', 'cost': 90,'color': 'Red'}
print(fruits)

Department of CSE, EPCET Page 22 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

[Link]('color', 'green')
print(fruits)

Output: {'name': 'Apple', 'cost': 90, 'color': 'Red'}

 The setdefault() method is a nice shortcut to ensure that a key exists. Here is a short program that
counts the number of occurrences of each letter in a string.
 Example
message = 'Application Development using Python Programming'
count = {}
for character in message:

.IN
[Link](character, 0)
count[character] = count[character] + 1
print(count)
C
#{'A': 1, 'p': 3, 'l': 2, 'i': 4, 'c': 1, 'a': 2, 't': 3, 'o': 4, 'n': 5, ' ': 4, 'D': 1, 'e': 3, 'v': 1, 'm': 3, 'u': 1, 's': 1,
N
'g': 3, 'P': 2, 'y': 1, 'h': 1, 'r': 2}
SY

 The program loops over each character in the message variable’s string, counting how often each
character appears. The setdefault() method call ensures that the key is in the count dictionary (with
U

a default value of 0) so the program doesn’t throw a KeyError error when count[character] =
VT

count[character] + 1 is executed.

2.9. Pretty Printing


 Using pprint module have access to the pprint() and pformat() functions that will “pretty print” a
dictionary’s values. This is helpful when you want a cleaner display of the items in a dictionary
than what print() provides.
 Example
import pprint
message = 'Application Development using Python Programming.'
count = {}
for character in message:
[Link](character, 0)

Department of CSE, EPCET Page 23 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

count[character] = count[character] + 1
[Link](count)
 The [Link]() function is especially helpful when the dictionary itself contains nested lists or
dictionaries.

.IN
2.10. Using Data Structures to Model Real-World Things
In algebraic chess notation, the spaces on the chessboard are identified by a number and letter coordinate
C
N
SY
U
VT

A Tic-Tac-Toe Board
 A tic-tac-toe board looks like a large hash symbol (#) with nine slots that can each contain an X,
an O, or a blank.
 To represent the board with a dictionary, you can assign each slot a string-value key. String values
'X', 'O', or ' ' (a space character) are used in each slot on the board which needs to store nine strings.
So, dictionary can be used. The string value with the key 'top-R' can represent the top-right corner,
the string value with the key 'low-L' can represent the bottom-left corner, the string value with the
key 'mid-M' can represent the middle, and so on.

Department of CSE, EPCET Page 24 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

The slots of a tic-tactoe board with their corresponding keys


 This dictionary is a data structure that represents a tic-tac-toe board. Store this board-as-a
dictionary in a variable named theBoard. Open a new file editor window, and enter the following
source code, saving it as [Link]:

.IN
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ', 'low-L': '
', 'low-M': ' ', 'low-R': ' '}

C
N
SY
U
VT

An empty tic-tac-toe board


theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': 'X', 'mid-R': ' ','low-L':
' ', 'low-M': ' ', 'low-R': ' '}

The First Move

Department of CSE, EPCET Page 25 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

theBoard = {'top-L': 'O', 'top-M': 'O', 'top-R': 'O', 'mid-L': 'X', 'mid-M': 'X', 'mid-R': ' ','low-
L': ' ', 'low-M': ' ', 'low-R': 'X'}

Player O wins

create a function to print the board dictionary onto the screen.

.IN
theBoard = {'top-L': 'O', 'top-M': 'O', 'top-R': 'O',
'mid-L': 'X', 'mid-M':'X', 'mid-R': ' ',
'low-L': ' ', 'low-M': ' ', 'low-R': 'X'}
def printBoard(board): C
N
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
SY

print('-+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
U

print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])


VT

printBoard(theBoard)

theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ', 'low-L': ' ', 'low-
M': ' ', 'low-R': ' '}
def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])

Department of CSE, EPCET Page 26 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

print('-+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
turn = 'X'
for i in range(9):
printBoard(theBoard)
print('Turn for ' + turn + '. Move on which space?')
move = input()
theBoard[move] = turn
if turn == 'X':
turn = 'O'
else:

.IN
turn = 'X'

printBoard(theBoard)

C
N
Nested Dictionaries and Lists
 In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries
SY

into one single dictionary.


nested_dict = { 'dictA': {'key_1': 'value_1'},
U

'dictB': {'key_2': 'value_2'}}


 Here, the nested_dict is a nested dictionary with the dictionary dictA and dictB. They are two
VT

dictionary each having own key and value.


 To access element of a nested dictionary, we use indexing [] syntax in Python.
people = {1: {'name': 'Raju', 'age': '36', 'sex': 'Male'}, 2: {'name': 'Manu', 'age': '8', 'sex': 'Male'}}
print(people[1]['name']) #Raju
print(people[1]['age']) #36
print(people[1]['sex']) #Male
allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
'Bob': {'ham sandwiches': 3, 'apples': 2},
'Carol': {'cups': 3, 'apple pies': 1}}
def totalBrought(guests, item):
numBrought = 0
for k, v in [Link]():

Department of CSE, EPCET Page 27 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

numBrought = numBrought + [Link](item, 0)


return numBrought
print('Number of things being brought:')
print(' - Apples ' + str(totalBrought(allGuests, 'apples')))
print(' - Cups ' + str(totalBrought(allGuests, 'cups')))
print(' - Cakes ' + str(totalBrought(allGuests, 'cakes')))
print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches')))
print(' - Apple Pies ' + str(totalBrought(allGuests, 'apple pies')))

 Number of things being brought:


- Apples 7

.IN
- Cups 3
- Cakes 0
- Ham Sandwiches 3
- Apple Pies 1
C
N
SY

Dictionary: Change Values


You can change the value of a specific item by referring to its key name:
>>> d = {"brand": "toyota", "model": "etios liva", "year": 2011 }
U

>>> d["year"] = 2018 #


VT

>>> print(d) # {'brand': 'toyota', 'model': 'etios liva', 'year': 2018

Loop Through a Dictionary


 Looping through a dictionary is done by using a for loop. To print all key names in the
dictionary, one by one:

for x in d:
print(x) # brand model year

 To print all values in the dictionary, one by one:


for x in d:
print(d[x]) # Toyota etios liva 2018

 You can also use the values() function to return values of a dictionary:

Department of CSE, EPCET Page 28 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

for x in [Link]():
print(x) # Toyota etios liva 2018

 items() function is used to loop through both keys and values


for x,y in [Link]():
print(x,y) #brand Toyota model etios liva year 2018

Dictionary: Check if Key Exists


 To determine if a specified key is present in a dictionary use the in keyword: Check if "model" is
present in the dictionary:
d = { "brand": "toyota", "model": "etios liva", "year": 2011 }

.IN
if "model" in d:
print("Yes, 'model' is one of the keys in the dictionary d")



C
To determine how many items (key-value pairs) a dictionary has, use the len() method.
Example: Print the number of items in the dictionary:
N
d = { "brand": "toyota", "model": "etios liva", "year": 2011 }
SY

print(len(d))

 Adding an item to the dictionary is done by using a new index key and assigning a value to it:
U

d = { "brand": "toyota", "model": "etios liva", "year": 2011 }


d["color"] = "White"
VT

print(d)
#{'brand': 'Toyota', 'model': 'Etios liva', 'year': 2011, 'color': 'White'}

Removing Items: pop()


 The pop() method removes the item with the specified key name:
d = {"brand": "toyota", "model": "etios liva", "year": 2011 }
[Link]("model")
print(d) # {'brand': 'Toyota', 'year': 2011}

Removing Items: popitem()


 The popitem() method removes the last inserted item (in versions before 3.7, a random item is
removed instead):

Department of CSE, EPCET Page 29 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

d = {"brand": "toyota", "model": "etios liva", "year": 2011 }


[Link]()
print(d) # {'brand': 'Toyota', 'model': 'Etios liva'}

Removing Items: del keyword


 The del keyword removes the item with the specified key name:
d = {"brand": "toyota", "model": "etios liva", "year": 2011 }
del d["model"]
print(d) #{'brand': 'Toyota', 'year': 2011}

 The del keyword can also delete the dictionary completely:

.IN
d = {"brand": "toyota", "model": "etios liva", "year": 2011 }
del d
print(d) #this will cause an error because "d" no longer exists.
C
N
Removing Items: clear()
 The clear() method empties the dictionary:
SY

d = {"brand": "toyota", "model": "etios liva", "year": 2011 }


[Link]()
print(d) #{ } empty dictionary but retains structure
U
VT

Copy a Dictionary
 Cannot copy a dictionary using dict2 = dict1, because: dict2 will only be a reference to dict1, and
changes made in dict1 will automatically reflects in dict2.
 To make a copy, use the built-in Dictionary method copy().
d = {"brand": "toyota", "model": "etios liva", "year": 2011 }
myd = [Link]()
print(myd)
# {'brand': 'Toyota', 'model': 'Etios liva', 'year': 2011}

Dictionary as a set of counters


word = 'Welcome'
d = dict()
for c in word:

Department of CSE, EPCET Page 30 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

if c not in d:
d[c] = 1
else:
d[c] = d[c] + 1
print(d)
# {'W': 1, 'e': 2, 'l': 1, 'c': 1, 'o': 1, 'm': 1}

 Dictionaries have a method called “get” that takes a key and a default value. If the key appears in
the dictionary, get returns the corresponding value; otherwise it returns the default value.
 For example:
d = {"brand": "toyota", "model": "etios liva", "year": 2011 }

.IN
print([Link]('year', 0)) #or print([Link]('year')) #2011
print([Link]('color', 0)) #0
print([Link]('color', 'white'))
C
#white
N
 The get method automatically handles the case where a key is not in a dictionary, we can reduce
four lines down to one and eliminate the if statement.
SY

word = 'welcome'
d = dict()
for c in word:
U

d[c] = [Link](c,0) + 1
VT

print(d) # {'w': 1, 'e': 2, 'l': 1, 'c': 1, 'o': 1, 'm': 1}


 If you use a dictionary as the sequence in a for statement, it traverses the keys of the dictionary.
This loop prints each key and the corresponding value:
d = {"brand": "Toyota", "model": "Etios liva", "year": 2011}
for key in d:
print(key, d[key]) #brand Toyota model Etios liva year 2011

Looping and dictionaries


 If you use a dictionary as the sequence in a for statement, it traverses the keys of the dictionary.
This loop prints each key and the corresponding value:
d = {"brand": "Toyota", "model": "Etios liva", "year": 2011}
for key in d:

Department of CSE, EPCET Page 31 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

print(key, d[key]) #brand Toyota model Etios liva year 2011

 Example: if we wanted to find all the entries in a dictionary with a value above ten, we could
write the following code:
counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}
for key in counts:
if counts[key] > 10 :
print(key, counts[key]) # annie 42 jan 100

 To print the keys in alphabetical order


counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}

.IN
lst = list([Link]())
print(lst) #['chuck', 'annie', 'jan']
[Link]()
for key in lst:
C
N
print(key, counts[key]) # annie 42 chuck 1 jan 100
SY

2.11. Manipulating Strings


 Strings are one of the most basic data types in Python, used to represent textual data.
 Every application involves working with strings, and Python’s str class provides a number of
U

methods to make string manipulation easy.


VT

 Strings are denoted with either single or double quotes.

2.12. Working with Strings


Working with Strings - String Literals
Strings are begin and end with a single quote.
name=‘Raju’
sem=‘fifth’

Working with Strings - Double Quotes


 Strings can begin and end with double quotes, just as they do with single quotes. One benefit of
using double quotes is that the string can have a single quote character in it.
>>> spam = "That is Alice's cat."

Department of CSE, EPCET Page 32 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

Working with Strings - Escape Characters


 An escape character lets you use characters that are otherwise impossible to put into a string. An
escape character consists of a backslash (\) followed by the character you want to add to the string.
 For example, the escape character for a single quote is \'. You can use this inside a string that
begins and ends with single quotes.
>>> spam = 'Say hi to Bob\'s mother.'

.IN
C
N
Working with Strings - Raw Strings
SY

 You can place an r before the beginning quotation mark of a string to make it a raw string. A raw
string completely ignores all escape characters and prints any backslash that appears in the string.
 Because this is a raw string, Python considers the backslash as part of the string and not as the start
U

of an escape Character.

VT

Raw strings are helpful if you are typing string values that contain many backslashes
>>> print(r'That is Carol\'s cat.')
Output: That is Carol\'s cat.

Multiline Strings with Triple Quotes


 A multiline string in Python begins and ends with either three single quotes or three double quotes.
Any quotes, tabs, or newlines in between the “triple quotes” are considered part of the string.
Python’s indentation rules for blocks do not apply to lines inside a multiline string.
print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob''')

Department of CSE, EPCET Page 33 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

 Single quote character in any word (ex: Eve's) does not need to be escaped. Escaping single and
double quotes is optional in raw strings. The following print() call would print identical text but
doesn’t use a multiline string:

print('Dear Alice,\n\nEve\'s cat has been arrested for catnapping, cat burglary, and
extortion.\n\nSincerely,\nBob')

 Hash character (#) marks the beginning of a comment till the end of line. A multiline string is
often used for comments that span multiple lines.
""" This is a test Python program.
Written by Al Sweigart al@[Link]

.IN
This program was designed for Python 3, not Python 2.
"""

def spam():
C
N
"""This is a multiline comment to help
SY

explain what the spam() function does."""


spam()
print('Hello!')
U
VT

Indexing and Slicing Strings


 Strings use indexes and slices the same way lists do. The string 'Hello world!' considered as a list
and each character in the string as an item with a corresponding index.
 The space and exclamation point are included in the character count, so 'Hello world!‘ is 12
characters long, from H at index 0 to ! at index 11.

‘ H e l l o w o r l d ! ‘

0 1 2 3 4 5 6 7 8 9 10 11

Indexing and Slicing Strings


>>> spam = 'Hello world!'
>>> spam[0] #'H'

Department of CSE, EPCET Page 34 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

>>> spam[3] #'l'


>>> spam[-1] #'!'
>>> spam[0:4] #'Hell'
>>> spam[:5] #'Hello'
>>> spam[2:] #'llo world!'
>>> spam[0:6:2] #'Hlo‘
>>> spam[0::2] #'Hlowrd'

 Slicing a string does not modify the original string. You can capture a slice from one variable in
to a separate variable.
>>> spam = 'Hello world!‘

.IN
>>> fizz=spam[0:4]
>>> fizz #'Hell'
>>> spam
C #'Hello world!'
N
The in and not in Operators with Strings
SY

 The in and not in operators can be used with strings just like with list values. An expression with
two strings joined using in or not in will evaluate to a Boolean True or False.
>>> 'Hello' in 'Hello World‘ #True
U

>>> 'Hello' in 'Hello‘ #True


>>> 'HELLO' in 'Hello World‘
VT

#False
>>> '' in 'spam‘ #True
>>> 'cats' not in 'cats and dogs‘ #False
>>> ' ' in 'spam‘ #False

2.13. Useful String Methods


The upper(), lower(), isupper(), and islower() String Methods
 The upper() and lower() string methods return a new string where all the letters in the original
string have been converted to uppercase or lower-case, respectively. Nonletter characters in the
string remain unchanged.
>>> spam = 'Hello world!'
>>> spam = [Link]()

Department of CSE, EPCET Page 35 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

>>> spam #'HELLO WORLD!'


>>> spam = [Link]()
>>> spam #'hello world!'

 The upper() and lower() methods are helpful if you need to make a case-insensitive comparison.
print('How are you?')
feeling = input()
if [Link]() == 'great':
print('I feel great too.')
else:
print('I hope the rest of your day is good.')

.IN
 The strings 'great' and 'GREat' are not equal to each other. But, it does not matter whether the user


C
types Great, GREAT, or grEAT, because the string is first converted to lowercase.
The isupper() and islower() methods will return a Boolean True value if the string has at least one
N
letter and all the letters are uppercase or lowercase, respectively. Otherwise, the method returns
SY

False.
>>> spam = 'Hello world!'
>>> [Link]() #False
U

>>> [Link]() #False


VT

>>> 'abc12345'.islower() #True


>>> '12345'.islower() #False
>>> '12345'.isupper() #False
 The upper() and lower() string methods themselves return strings, you can call string methods on
those returned string values as well. Expressions that do this will look like a chain of method
calls.
>>> spam = 'Hello world!'
>>> [Link]() #False
>>> [Link]() #False
>>> 'abc12345'.islower() #True
>>> '12345'.islower() #False
>>> '12345'.isupper() #False

Department of CSE, EPCET Page 36 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

>>> 'Hello'.upper() #'HELLO‘


>>> 'Hello'.upper().lower() #'hello'
>>> 'Hello'.upper().lower().upper() #'HELLO'
>>> 'HELLO'.lower() #'hello'
>>> 'HELLO'.lower().islower() #True

The isX String Methods


 isalpha() returns True if the string consists only of letters and is not blank.
 isalnum() returns True if the string consists only of letters and numbers and is not blank.
 isdecimal() returns True if the string consists only of numeric characters and is not blank.

.IN
isspace() returns True if the string consists only of spaces, tabs, and new-lines and is not blank.
 istitle() returns True if the string consists only of words that begin with an uppercase letter
followed by only lowercase letters.
>>> 'hello'.isalpha()
>>> 'hello123'.isalpha()
C #True
#False
N
>>> 'hello123'.isalnum() #True
SY

>>> 'hello'.isalnum() #True


>>> '123'.isdecimal() #True
>>> ‘ '.isspace() #True
U

>>> 'This Is Title Case'.istitle() #True


VT

>>> 'This Is Title Case 123'.istitle() #True


>>> 'This Is not Title Case'.istitle() #False
>>> 'This Is NOT Title Case Either'.istitle() #False

 Example
while True:
print('Enter your age:')
age = input()
if [Link]():
break
print('Please enter a number for your age.')
while True:

Department of CSE, EPCET Page 37 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

print('Select a new password (letters and numbers only):')


password = input()
if [Link]():
break
print('Passwords can only have letters and numbers.')

 The startswith() and endswith() methods return True if the string value they are called on begins
or ends (respectively) with the string passed to the method; Otherwise, they return False.
>>> 'Hello world!'.startswith('Hello') #True
>>> 'Hello world!'.endswith('world!') #True
>>> 'abc123'.startswith('abcdef') #False

.IN
>>> 'abc123'.endswith('12') #False
>>> 'Hello world!'.startswith('Hello world!') #True
>>> 'Hello world!'.endswith('Hello world!') #True

C
N
The join() and split() String Methods
 The join() method is useful when you have a list of strings that need to be joined together into a
SY

single string value.


 The join() method is called on a string, gets passed a list of strings, and returns a string.

U

The returned string is the concatenation of each string in the passed-in list. join() is called on a
string value and is passed a list value.
VT

>>> ', '.join(['cats', 'rats', 'bats']) #'cats, rats, bats'


>>> ' '.join(['My', 'name', 'is', 'Raju']) #'My name is Raju'
>>> 'ABC'.join(['My', 'name', 'is', 'Raju']) #'MyABCnameABCisABCRaju'

The join() and split() String Methods


 The split() method is called on a string value and returns a list of strings. By default, the string is
split wherever whitespace characters such as the space, tab, or newline characters are found.
>>> 'My name is Raju'.split() #['My', 'name', 'is', 'Raju']
 We can pass a delimiter string to the split() method to specify a different string to split upon.
>>> 'MyABCnameABCisABCRaju'.split('ABC') #['My', 'name', 'is',
'Raju']
>>> 'My name is Raju'.split('m') #['My na', 'e is Raju']

Department of CSE, EPCET Page 38 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

 A common use of split() is to split a multiline string along the newline characters.
>>> spam = '''Dear Alice,
How have you been? I am fine.
There is a container in the fridge
that is labeled "Milk Experiment".
Please do not drink it.
Sincerely,
Bob''‘
>>> [Link]('\n')

Justifying Text with rjust(), ljust(), and center()

.IN
 The rjust() and ljust() string methods return a padded version of the string they are called on,
with spaces inserted to justify the text. The first argument to both methods is an integer length
for the justified string.
>>> 'Hello'.rjust(10)
C#' Hello'
N
>>> 'Hello'.rjust(20) #' Hello'
SY

>>> 'Hello World'.rjust(20) #' Hello World'


 'Hello'.rjust(10) right-justify 'Hello' in a string of total length 10. 'Hello' is five characters, and
remaining five spaces will be added to its left and justified right.
U

 An optional second argument to rjust() and ljust() will specify a fill character other than a space
VT

character.
>>> 'Hello'.rjust(20, '*') #'***************Hello'
>>> 'Hello'.ljust(20, '-') #'Hello --------------‘
 The center() string method works like ljust() and rjust() but centers the text rather than justifying
it to the left or right.
>>> 'Hello'.center(20) #' Hello '
>>> 'Hello'.center(20, '=') #'=======Hello========'

 Example
def printPicnic(itemsDict, leftWidth, rightWidth):
print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-'))
for k, v in [Link]():

Department of CSE, EPCET Page 39 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

print([Link](leftWidth, '.') + str(v).rjust(rightWidth))


picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000}
printPicnic(picnicItems, 12, 5)
printPicnic(picnicItems, 20, 6)

 Example
---PICNIC ITEMS--
sandwiches.. 4
apples ....... 12
cups .......... 4
cookies..... 8000

.IN
-------PICNIC ITEMS-------
sandwiches .............. 4
apples ................ 12
cups ................... 4
C
N
cookies.............. 8000
SY

Removing Whitespace with strip(), rstrip(), and lstrip()


 The strip() string method will return a new string without any whitespace characters at the
U

beginning or end.

VT

The lstrip() and rstrip() methods will remove whitespace characters from the left and right ends,
respectively.
>>> spam = ' Hello World '
>>> [Link]() #'Hello World'
>>> [Link]() #’ Hello World'
>>> [Link]() #'Hello World '

 A string argument will specify which characters on the ends should be stripped.
>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'
>>> [Link]('ampS') #'BaconSpamEggs‘
>>> [Link]('Spam') #'BaconSpamEggs‘
>>> [Link]('pSma') #'BaconSpamEggs'

Department of CSE, EPCET Page 40 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

 Passing strip() the argument 'ampS' will tell it to strip occurences of a, m, p, and capital S from the
ends of the string stored in spam.
 The order of the characters in the string passed to strip() does not matter: strip('ampS') will do the
same thing as strip('mapS') or strip('Spam').
 The pyperclip module has copy() and paste() functions that can send text to and receive text from
your computer’s clipboard.
 Sending the output of your program to the clipboard will make it easy to paste it to an email, word
processor, or some other software.
 Pyperclip does not come with [Link] install it, run command prompt in administrator mode.
Go to the directory where python is installed and run the following command
pip install pyperclip

.IN
 Then, pyperclip module can be used.
>>> import pyperclip

C
>>> [Link]('Hello world!')
>>> [Link]()
N
or
SY

import pyperclip as pc
[Link]('Hello world!')
[Link]()
U
VT

2.14. Project: Password Locker


 Generally, people will have accounts on many different websites. It’s a bad habit to use the same
password for each of them because if any of those sites has a security breach, the hackers will learn
the password to all of your other accounts.
 It’s best to use password manager software on your computer that uses one master password to
unlock the password manager. Then you can copy any account password to the clipboard and paste
it into the website’s Password field.
Step 1: Program Design and Data Structures
Step 2: Handle Command Line Arguments
Step 3: Copy the Right Password

 Step 1: Program Design and Data Structures

Department of CSE, EPCET Page 41 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6', 'blog':


'VmALvQyKAxiVH5G8v01if1MLZF3sdt', 'luggage': '12345'}

 Step 2: Handle Command Line Arguments


PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6',
'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
'luggage': '12345'}
 Example
import sys
if len([Link]) < 2:
print('Usage: python [Link] [account] - copy account password')

.IN
[Link]()
account = [Link][1] # first command line arg is the account name
Step 3: Copy the Right Password
if account in PASSWORDS:
C
N
[Link](PASSWORDS[account])
SY

print('Password for ' + account + ' copied to clipboard.')


else:
print('There is no account named ' + account)
U

 Run the file in command prompt and pass email as value in command prompt
VT

m2_project-[Link] email
Password for email copied to clipboard

2.15. Project: Adding Bullets to Wiki Markup


 When editing a Wikipedia article, you can create a bulleted list by putting each list item on its own
line and placing a star in front.
 But say you have a really large list that you want to add bullet points to. You could just type those
stars at the beginning of each line, one by one. Or you could automate this task with a short Python
script.

Step 1: Copy and Paste from the Clipboard


a. Paste text from the clipboard

Department of CSE, EPCET Page 42 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

b. Do something to it
c. Copy the new text to the clipboard
Step 2: Separate the Lines of Text and Add the Star
Step 3: Join the Modified Lines

Step 1: Copy and Paste from the Clipboard


#! python3
# [Link] - Adds Wikipedia bullet points to the start
# of each line of text on the clipboard.
import pyperclip
text = [Link]()

.IN
# TODO: Separate lines and add stars.
[Link](text)
Step 2: Join the Modified Lines
C
The call to [Link]() returns all the text on the clipboard as one big string. If we used the
N
“List of Lists of Lists”
SY

'Lists of animals\nLists of aquarium life\nLists of biologists by author


abbreviation\nLists of cultivars'
Separate the Lines of Text and Add the Star
U

import pyperclip
VT

text = [Link]()
# Separate lines and add stars.
lines = [Link]('\n')
for i in range(len(lines)): # loop through all indexes in the "lines" list
lines[i] = '* ' + lines[i] # add star to each string in "lines" list
[Link](text)
Step 3: Join the Modified Lines
import pyperclip
text = [Link]()
# Separate lines and add stars.
lines = [Link]('\n')
for i in range(len(lines)): # loop through all indexes for "lines" list
lines[i] = '* ' + lines[i] # add star to each string in "lines" list

Department of CSE, EPCET Page 43 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

text = '\n'.join(lines)
[Link](text)
import pyperclip
text = [Link]() #text copied from project 1(prev prg) output
print(text)
# TODO: Separate lines and add stars.
[Link](text)
text = [Link]()
# Separate lines and add stars.
lines = [Link]('\n')
for i in range(len(lines)): # loop through all indexes in the "lines" list

.IN
lines[i] = '* ' + lines[i] # add star to each string in "lines" list
text = '\n'.join(lines)
[Link](text)
print(lines)
C
N
SY
U
VT

Department of CSE, EPCET Page 44 of 44

Common questions

Powered by AI

List element modification involves changing the value at a specific index using direct assignment like list[index] = new_value. Append() and insert() add new elements, while del and pop() remove them . In contrast, dictionary key-value pairs are modified by directly assigning a new value to a key (e.g., dict[key] = new_value). Additional methods like update() can update multiple keys at once, while methods like pop() remove a key-value. The operations in dictionaries are indexed by keys instead of position indices seen in lists .

Python lists allow for dynamic modeling by enabling addition, deletion, and modification of elements flexibly. For instance, elements can be appended using the append() method or inserted at specific positions using insert(), and they can be accessed or removed by their indexes with operations like del . Dictionaries provide dynamic modeling by allowing key-value pairs to be added, modified, and deleted, supporting operations like using the pop() method to remove items, setdefault() to ensure keys exist, and the get() method for safe retrieval of values . These features of lists and dictionaries support complex data structures for real-world data representation.

The get() method allows retrieval of a key's value with an optional default value if the key does not exist, preventing KeyErrors. setdefault(), on the other hand, sets a key with a default value only if the key doesn’t already exist. These methods are useful in scenarios like data processing where missing keys are common—they ensure smooth code execution without errors from absent keys. For instance, using get() to provide default values when compiling reports from data dictionaries helps avoid interruptive errors .

Accessing a list item using an index returns a single element, while using a slice returns a new list containing the elements from the specified start index up to but not including the end index. If one or both indices are omitted, the slice defaults to start from the beginning (if the start index is omitted) or end at the list's length (if the end index is omitted). For example, spam[2] accesses a single value, while spam[1:4] creates a new list with elements from index 1 to 3 inclusive. Leaving out indices like spam[:2] returns elements from the start up to index 1, and spam[1:] returns all elements from index 1 to the end of the list .

Nested lists extend the capabilities of basic lists by representing multi-dimensional data structures like matrices or tables. They allow access to individual sub-elements using multiple indices, providing a structured approach to handle complex datasets. However, challenges arise in terms of increased complexity in data manipulation tasks; navigating nested elements requires careful index management and understanding of the nested structure’s logic. Operations like flattening a nested list or mapping functions over nested elements require advanced iterative or recursive strategies .

Negative indexing begins counting from the end of the list, whereas positive indexing starts from the beginning. A negative index of -1 refers to the last element, -2 to the second last, and so forth. This allows for easy access to end-based elements without needing to know the list’s length, which can be useful for operations involving the last few elements of a list .

Using references instead of copies for lists and dictionaries means that changes made to the data structure through any reference affect all references, as they point to the same memory location. This can lead to unintended side effects, where modifications in one part of a program inadvertently impact another. To avoid such issues, a deep copy (e.g., using the copy() method for dictionaries) should be used when independent manipulation is required, ensuring that changes to one copy do not affect another .

Strings and tuples differ from lists primarily in their immutability; changes cannot be made to individual elements after creation, unlike lists which are mutable. This makes strings and tuples more suitable for fixed sequences of data, where integrity is critical. Tuples are often used as keys in dictionaries due to their hashable nature, while strings are used for text manipulation and storage. Lists, on the other hand, allow dynamic changes, expansions, and contractions, making them ideal for tasks where a variable collection of elements is needed .

The len() function returns the number of elements in a list, aiding in iteration and boundary setting. append() adds elements to the end of the list, allowing for growth without manually managing indices. pop() removes and returns a specified item, while popitem() (primarily used with dictionaries) removes the last item. Using these methods incorrectly, such as calling pop() on an index out of range, could lead to IndexErrors, or altering list length and indices without recalculating them might produce logic errors .

Pretty-printing a dictionary involves formatting it to be more readable by aligning key-value pairs in a structured format. This can be achieved using libraries such as pprint or methods like pretty print (available in some Python implementations), which automatically format nested structures into indented, cleanly spaced lines. Pretty-printing is useful in debugging, data analysis, and logging, where clear visibility of data structures is crucial for effective comprehension and decision-making .

You might also like