PP Module 2 - PPT
PP Module 2 - PPT
By:
Dr. Vaneeta M
Associate Professor & Head
Dept. of AIML
KSIT
1
Overview of Syllabus
Module 2:
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, Reference
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
Textbook 1: Chapters 4 – 6
2
List Chapter 4
Lists and tuples can contain multiple values, which makes
writing programs that handle large amounts of data easier.
3
List Data Type
• A list is a value that contains multiple values in an
ordered sequence.
• A list value refers to a list itself.
• A list value can be stored as a value to variable or passed
to function as a parameter.
• A list begins with an opening square bracket and ends
with a closing square bracket, []
• Values inside the list are also called items.
• Items are separated with commas
4
List Data Type
>>> [1, 2, 3]
[1, 2, 3]
>>> ['cat', 'bat', 'rat', 'elephant']
['cat', 'bat', 'rat', 'elephant']
>>> ['hello', 3.1415, True, None, 42]
['hello', 3.1415, True, None, 42]
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam
['cat', 'bat', 'rat', 'elephant']
5
List Data Type
Getting Individual Values in a List with Indexes
Say you have the list ['cat', 'bat', 'rat', 'elephant'] stored in a variable
named spam. The Python code spam[0] would evaluate to 'cat', and
spam[1] would evaluate to 'bat', and so on. 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.
6
List Data Type
>>> 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.' 7
List Data Type
11
List Data Type
• Getting a List from Another List with Slices Just as an index
can get a single value from a list, a slice can get several values from
a list, in the form of a new list. A slice is typed between square
brackets, like an index, but it has two integers separated by a colon.
Notice the difference between indexes and slices.
• spam[2] is a list with an index (one integer).
• spam[1:4] is a list with a slice (two integers).
• In a slice, the first integer is the index where the slice starts. The
second integer is the index where the slice ends. A slice goes up to,
but will not include, the value at the second index. A slice valuates
to a new list value.
12
List Data Type
13
List Data Type
• Getting a List from Another List with Slices As a shortcut, you
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, or the beginning of
the list.
• Leaving out the second index is the same as using the length of the
list, which will slice to the end of the list.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[:2]
Lists 81
['cat', 'bat']
>>> spam[1:]
['bat', 'rat', 'elephant’] >>> spam[:]
['cat', 'bat', 'rat', 'elephant'] 14
List Data Type
15
List Data Type
16
List Data Type
18
Working with Lists
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):’)
name = input()
if name == ‘’:
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
for name in catNames:
print(' ' + name)
19
Working with Lists
20
Working with Lists
21
Working with Lists
23
Working with Lists
The Multiple Assignment Trick
The multiple assignment trick (technically called tuple
unpacking) is a shortcut that lets you assign multiple variables
with the values in a list in one line of code. So instead of doing
this:
>>> cat = ['fat', 'gray', 'loud']
>>> size = cat[0]
>>> color = cat[1]
>>> disposition = cat[2]
you could type this line of code:
>>> cat = ['fat', 'gray', 'loud']
>>> size, color, disposition = cat
24
Working with Lists
25
Working with Lists
28
Working with Lists
The random.shuffle() function will reorder the items in a list. This
function modifies the list in place, rather than returning a new list.
>>> import random
>>> people = ['Alice', 'Bob', 'Carol', 'David']
>>> random.shuffle(people)
>>> people
['Carol', 'David', 'Alice', 'Bob']
>>> random.shuffle(people)
>>> people
['Alice', 'David', 'Bob', 'Carol']
29
Augmented Assignment Operators
>>> spam = 42
>>> spam += 1
>>> spam
43
30
Augmented Assignment Operators
31
Augmented Assignment Operators
The += operator can also do string and list concatenation, and the
*= operator can do string and list replication
>>> spam = 'Hello,'
>>> spam += ' world!'
>>> spam
'Hello world!'
>>> bacon = ['Zophie']
>>> bacon *= 3
>>> bacon
['Zophie', 'Zophie', 'Zophie']
32
Methods
A method is the same thing as a function, except it is
“called on” a value. For example, if a list value were
stored in spam, you would call the index() list method
on that list like so: spam.index('hello').
33
Methods
Finding a Value in a List with the index() Method
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 error.
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> spam.index('hello')
0
>>> spam.index('heyas')
3
>>> spam.index('howdy howdy howdy')
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
spam.index('howdy howdy howdy')
ValueError: 'howdy howdy howdy' is not in list
34
Methods
When there are duplicates of the value in the list, the index of
its first appearance is returned. Enter the following into the
interactive shell, and notice that index() returns 1, not 3:
>>> spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']
>>> spam.index('Pooka')
1
35
Methods
Adding Values to Lists with the append() and insert() Methods
To add new values to a list, use the append() and insert() methods.
>>> spam = ['cat', 'dog', 'bat']
>>> spam.append('moose')
>>> spam
['cat', 'dog', 'bat', 'moose']
36
Methods
The insert() method can insert a value at any index in the list.
The first argument to insert() is the index for the new value, and
the second argument is the new value to be inserted. Enter the
following into the interactive shell:
>>> spam = ['cat', 'dog', 'bat']
>>> spam.insert(1, 'chicken')
>>> spam
['cat', 'chicken', 'dog', 'bat']
37
Methods
Notice that the code is spam.append('moose') and spam.insert(1,
'chicken’), not spam = spam.append('moose') and spam = spam.insert(1,
'chicken’).
Neither append() nor insert() gives the new value of spam as its return
value. (In fact, the return value of append() and insert() is None, so you
definitely wouldn’t want to store this as the new variable value.)
38
Methods
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.
>>> eggs = 'hello'
>>> eggs.append('world')
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
eggs.append('world')
AttributeError: 'str' object has no attribute 'append'
>>> bacon = 42
>>> bacon.insert(1, 'world')
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
bacon.insert(1, 'world')
AttributeError: 'int' object has no attribute 'insert'
39
Methods
If the value appears multiple times in the list, only the first
instance of the value will be removed. Enter the following into
the interactive shell:
>>> spam = ['cat', 'bat', 'rat', 'cat', 'hat', 'cat']
>>> spam.remove('cat')
>>> spam
['bat', 'rat', 'cat', 'hat', 'cat']
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 useful
when you know the value you want to remove from the list.
41
Methods
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. For
example, enter the following into the interactive shell:
>>> spam = [2, 5, 3.14, 1, -7]
>>> spam.sort()
>>> spam
[-7, 1, 2, 3.14, 5]
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> spam.sort()
>>> spam
['ants', 'badgers', 'cats', 'dogs', 'elephants']
42
Methods
You can also pass True for the reverse keyword argument to have
sort() sort the values in reverse order.
>>> spam.sort(reverse=True)
>>> spam
['elephants', 'dogs', 'cats', 'badgers', 'ants']
43
Methods
There are three things you should note about the sort() method.
1. The sort() method sorts the list in place; don’t try to capture the return value
by writing code like spam = spam.sort().
2. Cannot sort lists that have both number values and string values in them,
>>> spam = [1, 3, 2, 4, 'Alice', 'Bob']
>>> spam.sort()
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
spam.sort()
TypeError: '<' not supported between instances of 'str' and 'int’
3. 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']
>>> spam.sort()
>>> spam
['Alice', 'Bob', 'Carol', 'ants', 'badgers', 'cats']
44
Methods
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']
>>> spam.sort(key=str.lower)
>>> spam
['a', 'A', 'z', 'Z’]
Reversing the Values in a List with the reverse() Method
If you need to quickly reverse the order of the items in a list, you can call the
reverse() list method. Enter the following into the interactive shell:
>>> spam = ['cat', 'dog', 'moose']
>>> spam.reverse()
>>> spam
['moose', 'dog', 'cat']
45
Sequence Data Types
Strings and lists are actually similar if you consider a string to
be a “list” of single text characters.
The Python sequence data types include lists, strings, range
objects returned by range(), and tuples. Many of the things you
can do with lists can also be done with strings and other values
of sequence types: indexing; slicing; and using them with for
loops, with len(), and with the in and not in operators.
46
Sequence Data Types
>>> name = 'Zophie'
>>> name[0]
'Z'
>>> name[-2]
'i'
>>> name[0:4]
'Zoph'
>>> 'Zo' in name
True
>>> 'z' in name
False
>>> 'p' not in name
False
>>> for i in name:
... print('* * * ' + i + ' * * *') 47
Sequence Data Types
48
Sequence Data Types
49
Sequence Data Types
50
Sequence Data Types
If you wanted to actually modify the original list in eggs to
contain [4, 5, 6], you would have to do something like this:
>>> eggs = [1, 2, 3]
>>> del eggs[2]
>>> del eggs[1]
>>> del eggs[0]
>>> eggs.append(4)
>>> eggs.append(5)
>>> eggs.append(6)
>>> eggs
[4, 5, 6]
51
Sequence Data Types
But the main way that tuples are different from lists is that
tuples, like strings, are immutable. Tuples cannot have their
values modified, appended, or removed.
>>> eggs = ('hello', 42, 0.5)
>>> eggs[1] = 99
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
eggs[1] = 99
TypeError: 'tuple' object does not support item assignment
53
Sequence Data Types
If you have only one value in your tuple, you can indicate
this by placing a trailing comma after the value inside the
parentheses. Otherwise, Python will think you’ve just
typed a value inside regular parentheses. The comma is
what lets Python know this is a tuple value.
>>> type(('hello',))
<class 'tuple'>
>>> type(('hello'))
<class 'str'>
54
Sequence Data Types
55
Sequence Data Types
Converting Types with the list() and tuple() Functions
Just like how str(42) will return '42', the string representation of the
integer 42, the functions list() and tuple() will return list and tuple
versions of the values passed to them.
>>> tuple(['cat', 'dog', 5])
('cat', 'dog', 5)
>>> list(('cat', 'dog', 5))
['cat', 'dog', 5]
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
56
Chapter 5
Dictionaries and Structuring Data
57
The Dictionary Data Type
58
The Dictionary Data Type
A dictionary is typed with braces, {}.
>>> myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud’}
This assigns a dictionary to the myCat variable. This dictionary’s keys are
'size', 'color', and 'disposition'. The values for these keys are 'fat', 'gray’,
and 'loud', respectively. You can access these values through their keys:
>>> myCat['size']
'fat'
>>> 'My cat has ' + myCat['color'] + ' fur.'
'My cat has gray fur.'
Dictionaries can still use integer values as keys, just like lists use integers
for indexes, but they do not have to start at 0 and can be any number.
>>> spam = {12345: 'Luggage Combination', 42: 'The Answer'}
59
The Dictionary Data Type
60
The Dictionary Data Type
61
The Dictionary Data Type
Because dictionaries are not ordered, they can’t be sliced like lists.
Trying to access a key that does not exist in a dictionary will result
in a KeyError error message, much like a list’s “out-of-range”
IndexError errormessage.
>>> spam = {'name': 'Zophie', 'age': 7}
>>> spam['color']
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
spam['color']
KeyError: 'color'
62
The Dictionary Data Type
birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}
while True:
print('Enter a name: (blank to quit)’)
name = input()
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.') 63
The Dictionary Data Type
Enter a name: (blank to quit)
Alice
Apr 1 is the birthday of Alice
Enter a name: (blank to quit)
Eve
I do not have birthday information for Eve
What is their birthday?
Dec 5
Birthday database updated.
Enter a name: (blank to quit)
Eve
Dec 5 is the birthday of Eve
Enter a name: (blank to quit)
64
The Dictionary Data Type
The keys(), values(), and items() Methods
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().
The values returned by these methods are not true lists: they cannot be modified
and do not have an append() method.
But these data types (dict_keys, dict_values, and dict_items, respectively) can be used
in for loops.
>>> spam = {'color': 'red', 'age': 42}
>>> for v in spam.values():
... print(v)
red
42
65
The Dictionary Data Type
66
The Dictionary Data Type
• When you use the keys(), values(), and items() methods, a for
loop can iterate over the keys, values, or key-value pairs in a
dictionary, respectively.
• Notice that the values in the dict_items value returned by the
items() method are tuples of the key and value.
• If you want a true list from one of these methods, pass its list-
like return value to the list() function.
>>> spam = {'color': 'red', 'age': 42}
>>> spam.keys()
dict_keys(['color', 'age'])
>>> list(spam.keys())
['color', 'age']
67
The Dictionary Data Type
68
The Dictionary Data Type
70
The Dictionary Data Type
71
The Dictionary Data Type
72
The Dictionary Data Type
The setdefault() method offers a way to do this in one line of code. The
first argument passed to the method is the key to check for, and the
second argument is the value to set at that key if the key does not exist.
If the key does exist, the setdefault() method returns the key’s value.
>>> spam = {'name': 'Pooka', 'age': 5}
>>> spam.setdefault('color', 'black')
'black'
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}
>>> spam.setdefault('color', 'white')
'black'
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}
73
The Dictionary Data Type
• The first time setdefault() is called, the dictionary in spam changes to
{'color': 'black', 'age': 5, 'name': 'Pooka'}. The method returns the value
'black' because this is now the value set for the key 'color’.
• When spam.setdefault('color', 'white') is called next, the value for that
key is not changed to 'white', because spam already has a key named
'color’. 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.
74
The Dictionary Data Type
75
The Dictionary Data Type
{' ': 13, ',': 1, '.': 1, 'A': 1, 'I': 1, 'a': 4, 'c': 3, 'b': 1, 'e': 5, 'd': 3, 'g': 2,
'i': 6, 'h': 3, 'k': 2, 'l': 3, 'o': 2, 'n': 4, 'p': 1, 's': 3, 'r': 5, 't': 6, 'w': 2, 'y': 1}
76
The Dictionary Data Type
Pretty Printing
• If you import the pprint module into your programs, you’ll 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.
import pprint
message = 'It was a bright cold day in April, and the clocks were striking
thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
77
The Dictionary Data Type
78
The Dictionary Data Type
79