A long trip is coming, and Rocket needs the biggest fuel tank on the station. There are four tanks. "Let's just look at them all," he says, and he starts reading numbers out loud.
Raven grabs a sticky note. "What do you notice? I only write down a number when I find a bigger one."
Nova draws a glowing crown above the first tank. "Interesting! Would you like a hint? Keep a champion. Swap it whenever a bigger value comes along."
Start with the first item as the champion. Then loop through the list.
If an item is bigger than the champion, it becomes the new champion.
tanks = [40, 75, 30, 60]
biggest = tanks[0]
for t in tanks:
if t > biggest:
biggest = t
print("Biggest tank:", biggest) | The screen shows |
|---|
| Biggest tank: 75 |
| Round | t | t > biggest? | biggest after the round |
|---|---|---|---|
| before the loop | none yet | none yet | 40 |
| 1 | 40 | False | 40 |
| 2 | 75 | True | 75 |
| 3 | 30 | False | 75 |
| 4 | 60 | False | 75 |
tanks = [25, 18, 52, 47]
biggest = tanks[0]
for t in tanks:
if t > biggest:
biggest = t
print(biggest) A loop can also build a new list. Start empty, then append each item that matches.
tanks = [40, 15, 30, 10]
low = []
for t in tanks:
if t < 20:
low.append(t)
print(low)
print(len(low)) | The screen shows |
|---|
| [15, 10] |
| 2 |
temps = [14, 9, 21, 6, 12]
smallest = temps[0]
for t in temps:
if t < smallest:
smallest = t
print("Coldest:", smallest) | Statement | True or false? |
|---|---|
| The champion only changes when a better value comes. | ? |
| The champion changes every round. | ? |
| A loop can build a new list with append. | ? |
| The low list starts with one item in it. | ? |
You found the champion and collected the low tanks! Tomorrow you will debug choices that went wrong.