Collect the Cards You Missed
Many lists are not known when you write a program. Which scores were too low, which words were too long, which answers were wrong: these only become clear while the program runs. Python lets you start with a list that holds nothing, add items to it as you find them, and then count what you collected and check whether anything was collected at all.
Start empty, add to the end
A list is an ordered collection of values between square brackets. A pair of square brackets with nothing between them, [], is a list too: the empty list, a list with no items yet. It is a real list, so you can give it a name and add to it later.
To add an item, you call the list's append method. A method is a function that belongs to a value and is called with a dot, so fruits.append('pear') means: take the list named fruits and put 'pear' at its end. Every call adds exactly one item, after all the items that are already there, so the list keeps the order in which the items arrived.
fruits = []
fruits.append('apple')
fruits.append('pear')
fruits.append('plum')
print(fruits)['apple', 'pear', 'plum']The same list changes after each line. Reading the program from top to bottom, this is what fruits holds after every step:
| Line that ran | fruits holds | Items |
|---|---|---|
| fruits = [] | [] | 0 |
| fruits.append('apple') | ['apple'] | 1 |
| fruits.append('pear') | ['apple', 'pear'] | 2 |
| fruits.append('plum') | ['apple', 'pear', 'plum'] | 3 |
Notice that append changes the list itself. It does not make a new list that you would have to store under a name, so the call stands alone on its line.
The call still gives something back: None, Python's value for "nothing". That is why writing fruits = fruits.append('fig') is a mistake. The list does get the new item, but then the name fruits is made to refer to None, and the list is lost.
True or false?
Each call to append puts the new item after all the items the list already holds.
True. append always adds at the end, so the items stay in the order they were added.
Writing fruits = fruits.append('fig') keeps the longer list in fruits.
False. append changes the list and gives back None, so this line makes fruits refer to None. Call fruits.append('fig') on its own instead.
fruits.append(['fig', 'kiwi']) adds two items to fruits.
False. append adds exactly one item. Here that one item is the whole list ['fig', 'kiwi'], which now sits inside fruits as its last item.
Collect the items that pass a test
Growing a list one line at a time becomes useful when you join it with a for loop and an if. The loop walks through a list you already have, one item per round. In each round, an if asks a question about the current item, and only when the answer is True does the item get appended to a second list. When the loop ends, the second list holds exactly the items that passed.
Here the test is "is this score below 50?":
scores = [72, 45, 90, 38, 61]
low = []
for score in scores:
if score < 50:
low.append(score)
print(low)[45, 38]- low = [] before the loop
- Take the next score
- score < 50?
- low.append(score)
- After the loop low holds every low score
- low = [] to Take the next score
- Take the next score to score < 50?
- score < 50? to low.append(score): True
- score < 50? to Take the next score: False
- low.append(score) to Take the next score
- Take the next score to After the loop: no scores left
Following the loop round by round shows how low grows only in the rounds where the test is True, and simply keeps what it has in the others:
| Round | score | score < 50 | low after the round |
|---|---|---|---|
| 1 | 72 | False | [] |
| 2 | 45 | True | [45] |
| 3 | 90 | False | [45] |
| 4 | 38 | True | [45, 38] |
| 5 | 61 | False | [45, 38] |
Two details make this pattern work. First, the line low = [] sits before the loop, so it runs once. If it were inside the loop, every round would start low over as an empty list, and only what the last round added would survive.
Second, the original list is left alone: scores still holds all five numbers afterwards. It can be tempting to remove the items you do not want from the list you are looping over, but the Python documentation advises against changing a list while looping over it, because that is hard to get right. Making a new list is simpler and safer.
The test can be any condition you could write in an if: a comparison, a check on a string, or several conditions joined with and, or and not.
True or false?
If low = [] is moved inside the for loop, low still holds every low score when the loop ends.
False. Inside the loop the line runs in every round and empties low each time. After the last round, low holds only what that round added: here nothing, because 61 is not below 50.
After the loop, scores still holds all five numbers.
True. The loop only reads scores. The items that passed were added to a different list, low.
Count the items with len
Once a program has collected items, it often needs to know how many there are. The function len, which is built into Python and always available, gives the number of items in a list. You call it like print, with the list between the parentheses: len(low). It is not a method, so it is not written after a dot.
low = [45, 38]
print(len(low))
print(len([]))
print(f"{len(low)} scores are below 50.")2
0
2 scores are below 50.The result is a whole number, so you can compare it, compute with it or put it in an f-string, as the last line does. An empty list has length 0, and every call to append makes the length one larger, which is why the count always matches the number of items that passed the test.
True or false?
len(low) and low.len() are two ways to ask for the length of low.
False. len is a built-in function that takes the list as its argument. Lists have no len method, so only len(low) works.
After three calls to append on an empty list, len gives 3.
True. The empty list has length 0, and each append adds exactly one item.
An empty list counts as False
After collecting, a program usually has to choose between two cases: something was collected, or nothing was. You could write if len(low) == 0:, and it works. Python also offers a shorter way, because a condition does not have to be a comparison.
Wherever Python expects a condition, in an if or a while, you may put any value there. Python then decides whether that value counts as true or false.
For a list, the rule is about its length alone. A list with no items counts as False. A list with at least one item counts as True, whatever that item is, even an empty string, a zero or False itself.
| The list | len | In a condition it counts as |
|---|---|---|
| [] | 0 | False |
| [0] | 1 | True |
| [''] | 1 | True |
| [False] | 1 | True |
| [45, 38] | 2 | True |
So if low: reads as "if low holds anything", and the else branch covers the empty case:
if low:
print(f"{len(low)} scores are below 50.")
else:
print("Every score is 50 or more.")With low = [45, 38] this prints 2 scores are below 50., and with low = [] it prints Every score is 50 or more. When only the empty case needs special handling, not turns the test around: if not low: runs its block exactly when the list is empty. Both forms say the same thing as len(low) == 0, more briefly, and you will see them often in Python code.
True or false?
The block under if not low: runs exactly when low has no items.
True. An empty list counts as False, and not turns that into True. Any list with an item counts as True, so not makes it False.
The list [0] counts as False in a condition, because its only item is zero.
False. Only the length matters for a list. [0] has one item, so it counts as True.