Chapter 3 · Data
Lists
Step 1 of 22 · Concept
A list keeps items in order
In this lesson you keep many values in one list, change it, and see when two names share it.
names = ["Ada", "Alan", "Grace"]
- A list is values in
[...], in order. Each cell holds an arrow to its object. - Index, slice and
lenwork as on text:names[0]is"Ada",names[-1]is"Grace",len(names)is 3. list(range(5))is[0, 1, 2, 3, 4].
Like a name's box, a cell may show a number inside it (lesson 3's shorthand). Really, it holds an arrow.
Step 2 of 22 · Concept
A list can change
Text never changes, but a list can. Each of these changes the list itself:
| write | does to names |
|---|---|
names.append("Linus") | adds "Linus" at the end |
names.insert(0, "Ida") | puts "Ida" at index 0; the rest move up one |
names.remove("Alan") | removes the first "Alan" |
names[0] = "Joan" | points cell 0 at "Joan" |
del names[1] | removes the item at index 1 |
names.pop() removes the last item and returns it.
Step 3 of 22 · Quiz
Predict the list
print shows a list in square brackets, each text in quotes, as lesson 9's split() showed. Type exactly what this
program prints.
names = ["Ada", "Alan", "Grace"]
names.append("Linus")
names.insert(0, "Ida")
names.remove("Alan")
names[0] = "Joan"
del names[1]
print(names.pop())
print(names)
Step 4 of 22 · Demo
See it run
Run it and compare with your answer. Then add print(names) after each line to watch the list change.
Step 5 of 22 · Quiz
Why did it stop?
This program printed three numbers, then stopped.
items = [1, 2, 3]
for i in range(4):
print(items[i])
1
2
3
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(items[i])
~~~~~^^^
IndexError: list index out of range
Why did it stop?
Step 6 of 22 · Exercise
Your turn: a shopping list
- Add
"bread", then"tea", at the end. - Remove
"eggs". - Put
"apples"at the front.
The program must print:
['apples', 'milk', 'bread', 'tea']
4 items
Each step is one call on shopping, written on its own line.
append adds at the end, remove takes a value away, insert(0, ...) puts a value at index 0.
shopping.insert(0, "apples")
Step 7 of 22 · Concept
for walks through a list
for score in scores: runs its block once for each item, as for ch in word: did for text (lesson 9).
scores = [70, 85, 90, 75]
for score in scores:
print(score)
| call | gives |
|---|---|
sum(scores) | 320, the total |
min(scores), max(scores) | 70 and 90 |
85 in scores, 60 not in scores | True, True |
Step 8 of 22 · Try it
Try it: a name that hides sum
Run it. It prints the total, then stops: TypeError: 'int' object is not callable. The name sum now points at
a number.
Rename that name to total in lines 2, 4 and 5. Leave sum(scores) alone.
Line 2 made sum point at 0, so Python no longer finds the function sum. A name of your own fixes it.
Step 9 of 22 · Exercise
Your turn: the scores over 50
Build a new list over with each score over 50, in order. Then print it and its total. The program must print:
[72, 91, 66]
229
Go through scores one score at a time, and keep the ones over 50. 50 itself is not over 50.
A for loop over scores, an if with > inside it, and append inside the if.
over.append(score)
Step 10 of 22 · Concept
= does not copy a list
a = [1, 2, 3]
b = a
c = a.copy()
b.append(4)
b = acopies the arrow, not the list.b.append(4)changes the listashows too.a.copy(),list(a)anda[:]each make a second list.a is basks "the same object?"a == casks "equal values?"
Step 11 of 22 · Quiz
Predict the three lists
Type exactly what this program prints.
a = [1, 2, 3]
b = a
c = a.copy()
print(a is b, a == c, a is c)
b.append(9)
print(a)
print(b)
print(c)
Step 12 of 22 · Demo
See it run
Run it and compare with your answer. Then change line 3 to c = a[:], then to c = a, and run it each time.
Step 13 of 22 · Concept
+ makes a new list, += extends this one
Two ways to add to a list, and they differ:
a = [1, 2]
a = a + [3]
a += [4]
a + [3]makes a new list,[1, 2, 3]. Thena = ...movesa's arrow to it, asx = x + 1does with numbers (lesson 3).a += [4]extends the listapoints at. No new list is made.
The difference shows when a second name points at the old list.
Step 14 of 22 · Quiz
Predict both names
b = a gives the list a second name: = never copies a list. Type exactly what this program prints.
a = [1, 2]
b = a
a += [3]
a = a + [4]
print(a)
print(b)
Step 15 of 22 · Demo
See it run
Run it and compare with your answer. Then swap lines 3 and 4 and run it again: now b keeps [1, 2].
Step 16 of 22 · Trace
A function changes your list
A call copies the arrow (lesson 7). This time the arrow points at a list. The drawing leaves out the name
add_bonus.
Press Next to run one moment at a time.
def add_bonus(marks):
marks.append(5)
return len(marks)
scores = [70, 80]
count = add_bonus(scores)
print(count, scores)- Lines 1 to 3 made the function
add_bonus. Line 5 is next. - Line 5 bound
scoresto a new list,[70, 80]. Line 6 callsadd_bonus(scores). - A frame for
add_bonusis on the stack. Itsmarkspoints at the same list asscores. Line 2 is next. marks.append(5)changed that one list: it is[70, 80, 5]. Line 3 is next.returnhanded3back, andadd_bonus's frame is gone. Back on line 6,countgets it.- Line 6 bound
countto 3.scoresstill points at the changed list. Line 7 is next. - Line 7 printed
3 [70, 80, 5]. The program is finished, and the stack is empty.
Step 17 of 22 · Quiz
Predict the defaults
add has a default list (lesson 7); both calls leave items out. add_safe makes its list inside. Type exactly
what this program prints.
def add(item, items=[]):
items.append(item)
return items
def add_safe(item, items=None):
if items is None:
items = []
items.append(item)
return items
first = add(1)
second = add(2)
print(first, second)
print(add_safe(1), add_safe(2))
Step 18 of 22 · Demo
A default list is made once
A default value is made once, when def runs. So a default list is shared by every call that leaves it out. Use
None as the default and make the list inside, as add_safe does.
Run it and compare with your answer.
Step 19 of 22 · Exercise
Your turn: a new list, the old one kept
Finish doubled(xs): it returns a new list with each number of xs times 2, and leaves xs as it was. The
program must print:
[1, 2, 3]
[2, 4, 6]
If nums prints [2, 4, 6] too, the function changed the caller's list. Build a second list instead.
Start an empty list in the function. Loop over xs, append each number times 2, then return the new list.
result.append(x * 2)
Step 20 of 22 · Check yourself
Check yourself: a class's scores
- Make
best, a copy ofscores. - Remove the lowest score from
best. - Print
scoresand its average, thenbestand its average.
The output must be exactly:
[60, 90, 80, 70] 75.0
[90, 80, 70] 80.0
If both lines show three scores, best is a second name for the list, not a copy.
Step 21 of 22 · Challenge · optional
Challenge: each name once
Optional.
Make unique, a new list with each name once, in the order the names first appear. Then print each name of
unique with how many times it is in names. The program must print:
['Ada', 'Alan', 'Grace']
Ada 2
Alan 2
Grace 1
Go through names. Add a name only when it is not in unique yet. Then loop over unique to print.
A list has a count method too, as text has (lesson 9): names.count("Ada") is how many times "Ada" is in it.
print(name, names.count(name))
Step 22 of 22 · Recap
Recap
- A list keeps items in order; each cell holds an arrow.
append,insert,remove,popanddelchange the list itself.a + [3]makes a new list;a += [3]extends the old one.b = agives one list two names;a.copy()makes a second list.- A function can change the caller's list. A default list is made once.
Next: lesson 11 groups values in tuples, stops loops early and puts lists in lists.
Review
5 questions from this lesson, in a new order each time. Answer from memory: 3 of 5 right on the first try passes. On a day after you finish the lesson, a pass earns 15 XP.
The review needs JavaScript.
names = ["Ada", "Alan", "Grace"]
names.append("Linus")
names.insert(0, "Ida")
names.remove("Alan")
names[0] = "Joan"
del names[1]
print(names.pop())
print(names)
shopping = ["milk", "eggs"]
# 1. add "bread", then "tea", at the end
# 2. remove "eggs"
# 3. put "apples" at the front
print(shopping)
print(len(shopping), "items")
scores = [70, 85, 90, 75]
sum = 0
for score in scores:
sum += score
print("Total:", sum)
print("sum() says:", sum(scores))
print("Best:", max(scores), "Worst:", min(scores))
print("Average:", sum(scores) / len(scores))
print(85 in scores, 60 not in scores)
print(scores[0], scores[1:], list(range(5)))
scores = [45, 72, 50, 91, 38, 66]
over = []
# add each score over 50 to over
print(over)
print(sum(over))
a = [1, 2, 3]
b = a
c = a.copy()
print(a is b, a == c, a is c)
b.append(9)
print(a)
print(b)
print(c)
a = [1, 2]
b = a
a += [3]
a = a + [4]
print(a)
print(b)
def add(item, items=[]):
items.append(item)
return items
def add_safe(item, items=None):
if items is None:
items = []
items.append(item)
return items
first = add(1)
second = add(2)
print(first, second)
print(add_safe(1), add_safe(2))
def doubled(xs):
# return a new list: each number times 2
return xs
nums = [1, 2, 3]
twice = doubled(nums)
print(nums)
print(twice)
scores = [60, 90, 80, 70]
# a copy without the lowest, then both averages
names = ["Ada", "Alan", "Ada", "Grace", "Alan"]
unique = []
# add each name once, then print each count
print(unique)