---
title: "Python for Loops: enumerate, zip, Scoping and Generators"
description: "How Python for loops really work: the loop variable that outlives the loop, enumerate, zip, dicts, for/else, and generators for data too big for memory."
image: "https://cdn.sethserver.com/blog-images/for-loop-social-1794889103.jpg"
---

# Python for Loops: enumerate, zip, Scoping and Generators

```python
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

```python
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:

- You reuse a common name like `i` or `row` further down and read a stale value from a loop that finished forty lines ago.
- The list was empty. The body never ran, `name` was never assigned, and using it after the loop raises `NameError`. It passes every test and then fails for the one customer with no orders.

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

## When you want the index: enumerate

```python
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

```python
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

```python
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

```python
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:

```python
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

```python
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

```python
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](https://www.sethserver.com/python/read-file-line-by-line.html).

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

```python
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:

```python
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

- A `for` loop walks an iterable. It doesn't count.
- The loop variable is still alive after the loop, and was never created if the loop didn't run.
- `enumerate` for positions, `zip(..., strict=True)` for parallel lists, `.items()` for dicts.
- Never add to or remove from the list you're looping over.
- Generators give you one item at a time, exactly once.

Slices go well with all of this, for the times you only want part of a list. I wrote up [slice notation](https://www.sethserver.com/python/understanding-slice-notation.html) separately.

-Sethers


```json
{"@context": "https://schema.org", "@type": "BlogPosting", "headline": "Python for Loops: enumerate, zip, Scoping and Generators", "datePublished": "2020-12-01T00:00:00", "dateModified": "2026-11-17T16:08:06", "image": {"@type": "ImageObject", "url": "https://cdn.sethserver.com/blog-images/for-loop-social-1794889103.jpg", "width": 400, "height": 400}, "url": "https://www.sethserver.com/python/for-loop.html", "author": {"@type": "Person", "name": "Seth Black", "url": "https://www.linkedin.com/in/seth-black-tx"}, "publisher": {"@type": "Organization", "name": "Sethserver", "logo": {"@type": "ImageObject", "url": "https://www.sethserver.com/static/images/PaperAirplane512.png"}}, "description": "How Python for loops really work: the loop variable that outlives the loop, enumerate, zip, dicts, for/else, and generators for data too big for memory.", "articleSection": "Technology"}
{"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "sethserver", "item": "https://www.sethserver.com/"}, {"@type": "ListItem", "position": 2, "name": "Python", "item": "https://www.sethserver.com/python/"}, {"@type": "ListItem", "position": 3, "name": "Python for Loops: enumerate, zip, Scoping and Generators", "item": "https://www.sethserver.com/python/for-loop.html"}]}
```
