Lesson 5 · lists and for loops
Today’s orders
- 1. Story
- 2. Guess
- 3. Your turn
EllaThe order slips are everywhere. One is under Mochi.
KaiIf they were all in one list, I could count them.
SitaraA list keeps them in a row, and a loop visits each one.
A list holds many values. A for loop visits them one by one.
- 1. A list holds values inside [ ]
- 2. for item in orders: visits each one in turn
- 3. len( ) counts how many there are
cafe.py
Try: Add "scone" to the list, then run it again.
Read · about 1 minute
The basics, in plain words
A list holds many values. A for loop visits them one by one.
orders = ["latte", "coffee", "latte"]
for item in orders:
print("Making", item)
print(len(orders), "orders")- A list holds values inside [ ]
- for item in orders: visits each one in turn
- len( ) counts how many there are
- [ list ]
- Many values in one place, in order: ["latte", "coffee"].
- for item in list:
- Visits each value one by one and runs the indented lines for it.
- len( )
- Counts how many values are in a list.
Common slip: Changing the list while looping over it. Loop over it first, change it after.
Read all twelve Python basics with Sitara →