Python for AIPython 3.10+ · Pydantic 2.12
Dashboard
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
34 small wins to finish your pathNext lesson →

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:

python
for item in items:
    ...    # runs once per item

Looping over the tickets

Examplethe tickets list from the Lists lesson
tickets = [
    "I was charged twice for one order",
    "My parcel has not arrived",
    "How do I change my password?",
]
Example
for ticket in tickets:
    print("-", ticket)

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

Example
billing = 0
for ticket in tickets:
    if "charged" in ticket or "refund" in ticket:
        billing += 1

print("Billing tickets:", billing)

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

Example
for number, ticket in enumerate(tickets, start=1):
    print(f"{number}. {ticket}")

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

Example
for attempt in range(3):
    print("attempt", attempt)

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 ticketsfor i in range(len(tickets))
The loop getsEach ticketEach position, 0 to 2
Reads asWhat you meanExtra step: tickets[i]
Need the number tooUse enumerateAlready 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.
Watch out. Indentation decides what is inside the loop. A print indented under the loop runs once per ticket; the same line with no indent runs once, after the loop.
Try it yourself
  • Count the tickets that contain "parcel" as well.
  • In the enumerate example, change start=1 to start=100.
  • Move print("Billing tickets:", billing) inside the loop by indenting it. It now prints once per ticket.
PreviousLists

Slow is fine. Stopping is the only problem.