Introduction to Python Programming 21PLC15B/25B
Module 2 List and Dictionaries
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.
(Textbook 1: Chapters 4 – 5)
1. Explain the list data type with a suitable example program.
Hint:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[0]
'cat'
>>> spam[1]
'bat'
>>> spam[2]
'rat'
>>> spam[3]
'elephant'
>>> ['cat', 'bat', 'rat', 'elephant'][3]
'elephant'
>>> 'Hello ' + spam[0]
‘Hello cat'
>>> 'The ' + spam[1] + ' ate the ' + spam[0] + '.'
'The bat ate the cat.'
2. Explain the following in terms of python lists with suitable examples.
a. Negative Indicies
b. Slices and sublists
c. len() function
d. Modifying lists
e. List concatenation
f. List replication
g. del() function
Department of ECE, ATME College of Engineering, Mysuru Page 15
Introduction to Python Programming 21PLC15B/25B
h. in and not in operators
i. Multiple assignment
3. Explain the Augmented assignment operators.
Hint:
4. What are ASCII Values?
Department of ECE, ATME College of Engineering, Mysuru Page 16
Introduction to Python Programming 21PLC15B/25B
5. What are Methods? How are they different from functions? Exaplain with a suitable
example.
Hint:
• A method is the same thing as a function, except it is “called on” a value.
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> spam.index('hello')
0
6. Explain at least 4 methods for Lists.
Hint:
Methods for List type are:
• index()
o syntax: list_name.index(list_element)
o returns index of list_element’s first appearence
o Eg:
>>> spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']
>>> spam.index('Pooka')
1
<Complete similar explanation for rest of the methods>
• append()
• insert()
• remove()
• sort()
Department of ECE, ATME College of Engineering, Mysuru Page 17
Introduction to Python Programming 21PLC15B/25B
7. Explain mutable and immutable data types using tuples and lists.
Hint:
• A list value is a mutable data type: It can have values added, removed, or changed.
Eg:
>>> eggs = [1, 2, 3]
>>> eggs = [4, 5, 6]
>>> eggs
[4, 5, 6]
• Strings and Tuples are immutable: They cannot be changed.
>>> name = 'Zophie a cat'
>>> name[7] = 'the'
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
name[7] = 'the'
TypeError: 'str' object does not support item assignment
8. Explain the tuple datatype with a suitable example.
Hint:
• The tuple data type is almost identical to the list data type, except in two ways.
o tuples are typed with parentheses, ( and ), instead of square brackets, [ and ].
o tuples, like strings, are immutable. Tuples cannot have their values modified, appended, or
removed.
Eg:
>>> eggs = ('hello', 42, 0.5)
>>> eggs[1] = 99
Traceback (most recent call last):
File " pyshell#50", line 1, in <module>
eggs[1] = 99
TypeError: 'tuple' object does not support item assignment
o If only one value is in a tuple, this must be indicated by placing a trailing comma after the value
inside the parentheses.
Eg:
>>> type(('hello',))
<class ‘tuple’>
>>> type(('hello'))
Department of ECE, ATME College of Engineering, Mysuru Page 18
Introduction to Python Programming 21PLC15B/25B
<class ‘string’>
9. Explain the means of converting a list to a tuple and vice-versa.
Hint:
>>> tuple(['cat', 'dog', 5])
('cat', 'dog', 5)
>>> list(('cat', 'dog', 5))
['cat', 'dog', 5]
>>> list('hello') ['h', 'e', 'l', 'l', 'o']
10. What is a reference for a list?
Hint:
• When a list is assigned to a variable, it actually assigns a list reference to the variable.
• A reference is a value that points to some bit of data, and a list reference is a value that points to a list.
• A reference is an address used by the python interpreter to access the variables from the memory.
>>>spam = [0, 1, 2, 3, 4, 5]
>>>cheese = spam
>>>cheese[1] = 'Hello!'
>>>print('spam =',spam)
>>>print('cheese =',cheese)
Output:
spam = [0, 'Hello!', 2, 3, 4, 5]
cheese = [0, 'Hello!', 2, 3, 4, 5]
• Python uses references whenever variables must store values of mutable data types, such as
lists or dictionaries.
Department of ECE, ATME College of Engineering, Mysuru Page 19
Introduction to Python Programming 21PLC15B/25B
• For values of immutable data types such as strings, integers, or tuples, Python variables will
store the value itself
• To avoid
11. Elaborate passing of a reference using functions
Hint:
• References are used as the arguments that get passed to functions.
• When a function is called, the values of the arguments are copied to the parameter variables.
• Specifically, for lists and dictionaries, a copy of the reference is used for the parameter.
def eggs(someParameter):
someParameter.append('Hello')
spam = [1, 2, 3]
print('spam before eggs:',spam)
eggs(spam)
print('spam after eggs:',spam)
output:
spam before eggs: [1, 2, 3]
spam after eggs: [1, 2, 3, 'Hello']
• when eggs() is called, a return value is not used to assign a new value to spam. Instead, it modifies the
list in place, directly.
• Even though spam and someParameter contain separate references, they both refer to the same list.
12. Explain working with reference using copy method.
Hint:
Eg:
import copy
#%% create copy without copy method
spam = ['A', 'B', 'C', 'D']
cheese = spam
cheese.append('Ee')
print('spam after apppend:\n',spam)
print('cheese after append:\n',cheese)
Department of ECE, ATME College of Engineering, Mysuru Page 20
Introduction to Python Programming 21PLC15B/25B
#%%creating copy with copy method
cheese = copy.copy(spam)
cheese[1] = 42
print('spam after copy:\n',spam)
print('cheese after copy:\n',cheese)
output:
spam after apppend:
['A', 'B', 'C', 'D', 'Ee']
cheese after append:
['A', 'B', 'C', 'D', 'Ee']
spam after copy:
['A', 'B', 'C', 'D', 'Ee']
cheese after copy:
['A', 42, 'C', 'D', 'Ee']
13. Explain working with reference using deepcopy() method.
Hint:
#%% Without deppcopy
jam = ['a','A',12,['b',4,13.5]]
bread = copy.copy(jam)
print('jam is:',jam)
print('bread is:',bread)
print("bread[3][2] =",bread[3][2])
Department of ECE, ATME College of Engineering, Mysuru Page 21
Introduction to Python Programming 21PLC15B/25B
bread[3][2]=44
print("Changing bread[3][2]=44...now..")
print('jam is:',jam)
print('bread is:',bread)
Output:
jam is: ['a', 'A', 12, ['b', 4, 13.5]]
bread is: ['a', 'A', 12, ['b', 4, 13.5]]
bread[3][2] = 13.5
Changing bread[3][2]=44...now..
jam is: ['a', 'A', 12, ['b', 4, 44]]
bread is: ['a', 'A', 12, ['b', 4, 44]]
• Try using Deep Copy
#%% Using deepcopy
jam = ['a','A',12,['b',4,13.5]]
bread = copy.deepcopy(jam)
print('jam is:',jam)
print('bread is:',bread)
print("bread[3][2] =",bread[3][2])
bread[3][2]=44
print("Changing bread[3][2]=44...now..")
print('jam is:',jam)
print('bread is:',bread)
Output
jam is: ['a', 'A', 12, ['b', 4, 13.5]]
bread is: ['a', 'A', 12, ['b', 4, 13.5]]
bread[3][2] = 13.5
Changing bread[3][2]=44...now..
jam is: ['a', 'A', 12, ['b', 4, 13.5]]
bread is: ['a', 'A', 12, ['b', 4, 44]]
Department of ECE, ATME College of Engineering, Mysuru Page 22
Introduction to Python Programming 21PLC15B/25B
14. What are dictionary datatypes? Explain with a suitable example.
Hint:
• Dictionary is a collection of many values.
o Indexes for dictionaries are called keys.
o A key with its associated value is called a key-value pair.
• Dictionary is typed with braces, {}.
Ex:
myCat = {'size': 'fat', 'color': 'gray', 'disposition':
'loud'}
myCat['size']
'My cat has ' + myCat['color'] + ' fur.'
15. Explain the following methods for lists: keys(), values(), items()
• There are three dictionary methods that will return list-like values of the dictionary’s keys, values, or
both keys and values: keys(), values(), and items().
Ex:
myCat = {'size': 'fat', 'color': 'gray', 'disposition':
'loud'}
print('myCat.keys() prints:',myCat.keys())
print('\n\nmyCat.items() prints:',myCat.items())
print('\n\nmyCat.values() prints:',myCat.values())
Output:
myCat.keys() prints: dict_keys(['size', 'color',
'disposition'])
myCat.items() prints: dict_items([('size', 'fat'), ('color',
'gray'), ('disposition', 'loud')])
myCat.values() prints: dict_values(['fat', 'gray', 'loud'])
Department of ECE, ATME College of Engineering, Mysuru Page 23
Introduction to Python Programming 21PLC15B/25B
• The values returned by these methods are not true lists.
• They cannot be modified and do not have an append() method.
• These have data types (dict_keys, dict_values, and dict_items, respectively) can be used in for loops.
Ex:
myCat = {'size': 'fat', 'color': 'gray', 'disposition':
'loud'}
print('Type of type(myCat.keys()) is ',type(myCat.keys()))
print('Type of type(myCat.values()) is ',type(myCat.values()))
print('Type of type(myCat.items()) is ',type(myCat.items()))
Output:
print('Type of type(myCat.keys()) is ',type(myCat.keys()))
print('\nType of type(myCat.values()) is
',type(myCat.values()))
print('\nType of type(myCat.items()) is ',type(myCat.items()))
Department of ECE, ATME College of Engineering, Mysuru Page 24
Introduction to Python Programming 21PLC15B/25B
16. Explain the usage of dictionary methods with for loop using suitable examples.
Hint:
• Keys() method returns the dictionary key entires
Ex:
for v in myCat.keys():
print(v)
Output:
size
color
disposition
• Items() method returns all items i.e all key-value pairs
Ex:
for v in myCat.items():
print(v)
Output:
('size', 'fat')
('color', 'gray')
('disposition', 'loud')
• Values() returns only the values in each dictionary entry.
Ex:
for v in myCat.values():
print(v)
Output
fat
gray
loud
Department of ECE, ATME College of Engineering, Mysuru Page 25
Introduction to Python Programming 21PLC15B/25B
17. Explain the usage of in and not in operators for dictionaries with examples.
Hint:
myCat = {'size': 'fat', 'color': 'gray', 'disposition':
'loud'}
Expression Result
'fat' in myCat False
'fat' in myCat.items() False
'fat' in myCat.values() True
'color' in myCat.keys() True
<Explain not in operator with suitable example>
18. Explain the usage of get() method for dictionaries with a suitable example.
Hint:
myCat = {'name':'Ji-min','age(in yrs)': 4,'size': 'fat',
'color': 'gray', 'disposition': 'loud'}
'My cat '+ myCat.get('name',0) +' is of age ' +
str(myCat.get('age(in yrs)',0))+ '.'
Output:
'My cat Ji-min is of age 4.'
19. Explain the working and usage of the setdefault method for dictionary type.
Hint:
• Setdefault is used to set a value for a key only if that key does not already have a value.
• i.e. if previously a key exists and has a value then it will not be modified.
Ex:
#%% Existing key case
print('altering myCat\'s color to blue using setdefault()
method')
myCat.setdefault('color','blue')
print(myCat['color'])
Output:
altering myCat's color to blue using setdefault() method
gray
Department of ECE, ATME College of Engineering, Mysuru Page 26
Introduction to Python Programming 21PLC15B/25B
• Else if a key is not present then it may be assigned a default value using this method.
Ex:
#%% Setdefault() for non-existing key
myCat.setdefault('eyes','green')
print('myCat\'s eyes are colored '+myCat.get('eyes','0')+'.')
Output:
myCat's eyes are colored green.
20. Write a program to count the charecters in a sentence using the setdefault method
for dictionaries.
Hint:
import pprint
message = 'I love it when a plan comes together!!'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
Output:
{' ': 7,
'!': 2,
'I': 1,
'a': 2,
'c': 1,
'e': 5,
'g': 1,
'h': 2,
'i': 1,
'l': 2,
'm': 1,
'n': 2,
'o': 3,
'p': 1,
'r': 1,
's': 1,
't': 3,
'v': 1,
'w': 1}
Department of ECE, ATME College of Engineering, Mysuru Page 27