sethserver.com Subscribe
Python for Loops: enumerate, zip, Scoping and Generators

Python for Loops: enumerate, zip, Scoping and Generators

By Seth Black • Updated: November 17, 2026

Python · 4 min read

Like this kind of writing? Get one email a week with notes on startups, AI, and the occasional strong opinion about Python: subscribe to the newsletter.

pythons = ["Graham", "John", "Terry G", "Eric", "Terry J", "Michael"]

for name in pythons:
    print(f"It's {name}")

A for loop in Python doesn't count. There's no index, no i < len(...), no off-by-one error waiting for you. It asks the thing on the right for its items one at a time and runs the block once for each. Lists, strings, dicts, open files and database cursors all work the same way.

That one idea covers most of the loops you'll ever write. The rest of this post is the parts that surprise people.

The loop variable outlives the loop

for name in pythons:
    print(f"It's {name}")

print(f"Still {name}")  # Still Michael

name isn't scoped to the loop. A for loop doesn't create a scope at all, so when it ends, name is still sitting there holding the last item. If you come from C or Java, or from JavaScript's let, this looks like a bug. It's the documented behavior.

It bites in two ways:

Comprehensions are the exception. The variable in [n.upper() for n in pythons] stays inside the brackets.

When you want the index: enumerate

for position, name in enumerate(pythons, start=1):
    print(f"{position}. {name}")

If you catch yourself typing for i in range(len(pythons)):, stop and use enumerate. You get the position and the item together, and start=1 gives you human numbering without a + 1 scattered through the body.

Two lists at once: zip

born = [1941, 1939, 1940, 1943, 1942, 1943]

for name, year in zip(pythons, born, strict=True):
    print(f"{name} was born in {year}")

zip pairs the items up. Left alone, it stops at the end of the shorter list and says nothing, which is a quiet way to lose data when one list came up short. strict=True (Python 3.10 and later) raises a ValueError instead. I pass it any time the lengths are supposed to match.

Looping over a dict

roles = {"Graham": "King Arthur", "John": "Sir Lancelot", "Eric": "Sir Robin"}

for name, role in roles.items():
    print(f"{name} played {role}")

Looping over the dict itself gives you its keys. .items() gives you the pairs, and .values() gives you the values alone.

Don't change a list while you loop over it

numbers = [1, 2, 2, 3]

for n in numbers:
    if n == 2:
        numbers.remove(n)

print(numbers)  # [1, 2, 3]

One of the 2s survived. Removing an item slides everything after it one place to the left, the loop moves on to the next position anyway, and an element gets stepped over. There is no error. Build a new list instead:

numbers = [n for n in numbers if n != 2]

A dict at least tells you. Add or remove a key mid-loop and you get RuntimeError: dictionary changed size during iteration.

for ... else

for name in pythons:
    if name.startswith("Z"):
        print(f"Found {name}")
        break
else:
    print("Nobody starts with Z")

The else block runs when the loop finishes without hitting break. Read it as "no break." It's useful for search loops, and unusual enough that I leave a comment whenever I use it.

Generators: looping over things that don't exist yet

def read_orders(path):
    with open(path, encoding="utf-8") as handle:
        for line in handle:
            yield line.rstrip("\n").split(",")

for order in read_orders("orders.csv"):
    print(order)

A function with yield in it is a generator. Calling it runs nothing. The for loop asks for a value, the function runs until its next yield, hands the value over, and pauses right there until it's asked again. One line of the file is in memory at a time, whether there are a hundred orders or a hundred million. That's the trick behind reading a file line by line.

You can get the same laziness without writing a function. Swap the square brackets of a comprehension for round ones:

squares_list = [n * n for n in range(10_000_000)]  # builds ten million numbers right now
squares_gen = (n * n for n in range(10_000_000))   # builds nothing until you loop

The catch is that a generator only goes around once. The second loop over it gets nothing, and it doesn't complain:

evens = (n for n in range(10) if n % 2 == 0)

print(sum(evens))  # 20
print(sum(evens))  # 0

If you need the values twice, make a list. If you need them once and there are a lot of them, make a generator.

The short version

Slices go well with all of this, for the times you only want part of a list. I wrote up slice notation separately.

-Sethers

Share this post
Newsletter

One email, once a week.

Notes on databases, systems, and the occasional strong opinion about Python. No spam, unsubscribe anytime.

Seth Black
Written by

Seth Black

Engineer and founder based in Texas. Writes about databases, AI, and running things in production. Embeds in small teams as lead engineer.

More from Python

View all →
Python

Python Logging Done Right

Nov 18, 2026
Python

OpenAI Bought Astral - and my fav tool uv

Mar 23, 2026
Python

Python Pydantic Validation: Stop Writing Manual Checks

Mar 04, 2026