2. Topics Include
1. Lists 2. Dictionaries and
Structuring Data
3. Manipulating
Strings
a. The List Data Type, a. The Dictionary Data
type,
a. Working with Strings,
b. Working with Lists, b. Pretty Printing, b. Useful String
Methods,
c. Augmented
Assignment Operators,
c. Using Data Structures
to Model Real-World
Things
c. Project: Password
Locker,
d. Methods, d. Project: Adding
Bullets to Wiki Markup
e. Example Program:
Magic 8 Ball with a List,
f. List-like Types: Strings
and Tuples.
3. Objectives
● Explanation of what a list is.
● Create and index lists of simple values.
● Change the values of individual elements.
● Append values to an existing list.
● Reorder and slice list elements.
● List Concatenation and Replication.
● Multiple assignment Trick operator.
● Augmented assignment operators.
5. Chapter 4: Lists
● The list data type:
✔ A list is a value that contains multiple values in an ordered sequence.
Eg: ['cat', 'bat', 'rat', 'elephant'].
✔ Just as string values are typed with quote characters to mark where the
string begins and ends, 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
6. Hands-on with lists:
1. Typing on the console and observing the outputs:
>>> [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']
7. Getting Individual Values in a List with Indexes:
Let us consider a list ['cat', 'bat', 'rat', 'elephant'] stored in a variable named spam.
>>> 'Hello ' + spam[0]
'Hello cat‘
• Errors with List:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[10000]
Traceback (most recent call last): File "<pyshell#9>", line 1,
in <module>
spam[10000] IndexError: list index out of range
8. Integer values are accepted in lists, floating values are
not accepted
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[1]
'bat‘
>>> spam[1.0]
Traceback (most recent call last): File "<pyshell#13>",
line 1, in <module>
spam[1.0] TypeError: list indices must be integers, not float
>>> spam[int(1.0)]
'bat'
9. Lists can also contain other list values. The values in these lists of lists can be accessed using multiple
indexes
>>> spam = [['cat', 'bat'], [10, 20, 30, 40, 50]]
>>> spam[0]
['cat', 'bat']
>>> spam[0][1]
'bat‘
>>> spam[1][4]
50
10. Negative Indexes
● 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.
Enter the following into the interactive shell:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1]
‘elephant’
>>> spam[-3]
‘bat’
>>> 'The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.‘
'The elephant is afraid of the bat.'
11. Getting Sublists with Slices
● 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.
● 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 evaluates to a new list value.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[0:4]
['cat', 'bat', 'rat', 'elephant']
12. >>> spam[1:3]
['bat', 'rat']
>>> spam[0:-1]
['cat', 'bat', 'rat']
● 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,
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[:2]
['cat', 'bat']
>>> spam[1:] >>> spam[:]
['bat', 'rat', 'elephant'] ['cat', 'bat', 'rat', 'elephant']
13. ● 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 can count the number of characters in a string value.
>>> spam = ['cat', 'dog', 'moose']
>>> len(spam)
3
● Changing Values in a List with Indexes:
Normally a variable name goes on the left side of an assignment statement, like spam =
42. However, you can also use an index of a list to change the value at that index. For
example, spam[1] = 'aardvark' means “Assign the value at index 1 in the list spam to the
string 'aardvark'.”
15. ● List Concatenation and List Replication :
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']
16. ● Removing Values from Lists :
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]
>>> spam
['cat', 'bat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat']
17. ● Working with Lists:
Let us say you want to store the names of cats, at first what you do in a easy way is:
catName1 = 'Zophie'
catName2 = 'Pooka'
catName3 = 'Simon'
catName4 = 'Lady Macbeth'
catName5 = 'Fat-tail'
catName6 = 'Miss Cleo‘
Bad way to write the program if you have many cats, so what you can do is assign
variables and list the cats
18. print('Enter the name of cat 1:')
catName1 = input()
print('Enter the name of cat 2:')
catName2 = input()
print('Enter the name of cat 3:')
catName3 = input()
print('Enter the name of cat 4:')
catName4 = input()
print('Enter the name of cat 5:')
catName5 = input()
print('Enter the name of cat 6:')
catName6 = input()
print('The cat names are:')
print(catName1 + ' ' + catName2 + ' ' + catName3 + ' ' + catName4 + ' ' + catName5 + ' ' + catName6)
But,
What if you
want more than
6 cat names
Is this the
way to
write????
Again the answer
is no
19. ● Instead of using multiple, repetitive variables, you can use a single variable
that contains a list value.
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)
Output:
20. Enter the name of cat 1 (Or enter nothing to stop.):
Zophie
Enter the name of cat 2 (Or enter nothing to stop.):
Pooka
Enter the name of cat 3 (Or enter nothing to stop.):
Simon
Enter the name of cat 4 (Or enter nothing to stop.):
Lady Macbeth
Enter the name of cat 5 (Or enter nothing to stop.):
Fat-tail
Enter the name of cat 6 (Or enter nothing to stop.):
Miss Cleo
Enter the name of cat 7 (Or enter nothing to stop.):
The cat names are: Zophie Pooka Simon Lady Macbeth Fat-tail
Miss Cleo
21. ● 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)
Output:
0
1
2
3
A common Python technique is to use range(len(someList)) with a for loop to iterate
over the indexes of a list.
>>> supplies = ['pens', 'staplers', 'flame-throwers', 'binders']
>>> for i in range(len(supplies)):
print('Index ' + str(i) + ' in supplies is: ' + supplies[i])
22. ● The in and not in Operators :
Like other 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.
>>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas']
True
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> 'cat' in spam
False
>>> 'howdy' not in spam
False
>>> 'cat' not in spam
True
23. For example, the following program lets the user type in a pet name and then checks
to see whether the name is in a list of pets.
myPets = ['Zophie', 'Pooka', 'Fat-tail']
print('Enter a pet name:')
name = input()
if name not in myPets:
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.')
Output: Enter a pet name: Footfoot
I do not have a pet named Footfoot
24. ● The Multiple Assignment Trick :
The multiple assignment trick is a shortcut that lets you assign multiple variables with the
values in a list in one line of code.
>>> cat = ['fat', 'black', 'loud']
>>> size = cat[0]
>>> color = cat[1]
>>> disposition = cat[2]
you could type this line of code:
>>> cat = ['fat', 'black', 'loud']
>>> size, color, disposition = cat
The number of variables and the length of the list must be exactly equal, or Python will give
you a ValueError:
>>> cat = ['fat', 'black', 'loud']
>>> size, color, disposition, name = cat
25. ● Augmented Assignment Operators :
When assigning a value to a variable, you will frequently use the variable itself. For
example, after assigning 42 to the variable spam, you would increase the value in
spam by 1 with the following code: >>> spam = 42
>>> spam = spam + 1
>>> spam 43
As a shortcut, you can use the augmented assignment operator += to do the same
thing:
>>> spam = 42
>>> spam += 1
>>> spam
43
26. ● There are augmented assignment operators for the +, -, *, /, and % 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!
27. 1.
EXCERSISE
1. What is []?
2. How would you assign the value 'hello' as the third value in a list stored in a variable
named spam? (Assume spam contains [2, 4, 6, 8, 10].) For the following three questions,
let’s say spam contains the list ['a', 'b', 'c', 'd'].
3. What does spam[int('3' * 2) / 11] evaluate to?
4. What does spam[-1] evaluate to?
5. What does spam[:2] evaluate to?
For the following three questions, let’s say bacon contains the list [3.14, 'cat', 11, 'cat',
True].
28. 6. What does bacon.index('cat') evaluate to?
7. What does bacon.append(99) make the list value in bacon look like?
8. What does bacon.remove('cat') make the list value in bacon look like?
9. What are the operators for list concatenation and list replication?
10. What is the difference between the append() and insert() list methods?
EXCERSISE