for loops
A for loop is a statement that runs the same block once for each item in a list, with a name that holds the current item.
Last updated: 30 Sep, 2026 · Python 3.14
Sorting the tickets from Lists means doing the same step for each one. A for loop writes that step once.
Syntax:
for item in items:
... # runs once per itemLooping over the tickets
tickets = [
"I was charged twice for one order",
"My parcel has not arrived",
"How do I change my password?",
]for ticket in tickets:
print("-", ticket)- I was charged twice for one order - My parcel has not arrived - How do I change my password?
Read it as: for each item in tickets, call it ticket and run the indented lines. The name after for is yours to choose; the singular of the list's name is the usual habit.
Counting as you go
billing = 0
for ticket in tickets:
if "charged" in ticket or "refund" in ticket:
billing += 1
print("Billing tickets:", billing)Billing tickets: 1
billing += 1 is short for billing = billing + 1. The counter starts before the loop, grows inside it, and is printed after it, which is where the indentation of the last line matters.
Numbering the items with enumerate
for number, ticket in enumerate(tickets, start=1):
print(f"{number}. {ticket}")1. I was charged twice for one order 2. My parcel has not arrived 3. How do I change my password?
enumerate hands the loop two things each time, a count and the item, and the loop names both.
Repeating a set number of times with range
for attempt in range(3):
print("attempt", attempt)attempt 0 attempt 1 attempt 2
range(3) gives 0, 1 and 2. Timeouts and retries uses exactly this to try a model call again when it fails.
Looping over items vs range(len(...))
for ticket in tickets | for i in range(len(tickets)) | |
|---|---|---|
| The loop gets | Each ticket | Each position, 0 to 2 |
| Reads as | What you mean | Extra step: tickets[i] |
| Need the number too | Use enumerate | Already have it |
Where for loops show up in AI code
- Sending every ticket in a list to a model, one at a time.
- Counting how many answers were billing, or how many failed a check.
- Trying a call a few times with
range.
print indented under the loop runs once per ticket; the same line with no indent runs once, after the loop.Related
- Previous: Lists
- Next: Dictionaries
- Reference: for Statements in the Python tutorial
- Count the tickets that contain
"parcel"as well. - In the enumerate example, change
start=1tostart=100. - Move
print("Billing tickets:", billing)inside the loop by indenting it. It now prints once per ticket.
Slow is fine. Stopping is the only problem.