Start here
To iterate means to go through items one by one. You already do it with a for loop.
Anything a for loop can go through is called an iterable. A list is an iterable.
Here is the shop from the earlier chapters. One order is one row. In Python, one row is one dict.
| order_id | customer_id | status | amount |
|---|---|---|---|
| 101 | 1 | paid | 40 |
| 102 | 1 | paid | 25 |
| 103 | 2 | refunded | 60 |
| 104 | 3 | paid | 15.5 |
| 105 | 3 | pending | NULL |
| 106 | 4 | paid | 80 |
orders = [
{"order_id": 101, "customer_id": 1, "status": "paid", "amount": 40.0},
{"order_id": 102, "customer_id": 1, "status": "paid", "amount": 25.0},
{"order_id": 103, "customer_id": 2, "status": "refunded", "amount": 60.0},
{"order_id": 104, "customer_id": 3, "status": "paid", "amount": 15.5},
{"order_id": 105, "customer_id": 3, "status": "pending", "amount": None},
{"order_id": 106, "customer_id": 4, "status": "paid", "amount": 80.0},
]
for order in orders:
print(order["order_id"], order["status"])| output |
|---|
| 101 paid |
| 102 paid |
| 103 refunded |
| 104 paid |
| 105 pending |
| 106 paid |
Real data is not a list in your code. It is a file with many lines. The same shop, as a small CSV file, looks like this:
order_id,customer_id,status,amount
101,1,paid,40.0
102,1,paid,25.0
103,2,refunded,60.0
104,3,paid,15.5
105,3,pending,
106,4,paid,80.0We use both forms in this chapter. The list shows each idea in a few lines. The file shows how the idea works on real input.
In every example below, orders is the list above and orders.csv is this file. The page shows the printed output, so you only need to read.
What you will learn
- Why a loop that handles one row at a time beats loading all rows.
- How to write a generator with yield.
- Why a generator is used up after one pass.
- How to chain small steps into a pipeline.
- How to group rows into batches.
