1.2.18Introduction to Programming (Python)

for loop — iterating over sequences

1,814 words8 min readdifficulty · medium1 backlinks

WHAT exactly is happening

for item in sequence:
    # body: runs once per item
    print(item)

HOW the loop runs — derive it from scratch

A for loop is not magic; it is sugar for a while loop. Let's build it ourselves so the mechanism is undeniable.

for x in seq:
    body(x)

is exactly equivalent to:

_it = iter(seq)          # 1. get an iterator (a cursor at position 0)
while True:              # 2. loop forever...
    try:
        x = next(_it)    # 3. grab the next item, advance the cursor
    except StopIteration:
        break            # 4. ...until the sequence is empty -> stop
    body(x)              # 5. run the body with the current item
Figure — for loop — iterating over sequences

Worked examples


Common mistakes (Steel-manned)


Recall Feynman: explain to a 12-year-old

Imagine a lunchbox packed with snacks. A for loop is like a kid who takes out one snack at a time, does something with it (eats it, names it), then reaches in for the next — until the box is empty. The kid never needs to know how many snacks there are first; they just keep going until there's nothing left. That "reach in for the next one until empty" is exactly next() + StopIteration.


Flashcards

What does a for loop iterate over?
An iterable — list, str, tuple, range, dict, etc. — yielding one item per pass.
A for loop is sugar for which two functions?
iter() (once, to get an iterator) then repeated next() until StopIteration.
What signals the end of a for loop internally?
The iterator raising StopIteration, which the loop catches as a break.
What does range(2, 8) produce?
2, 3, 4, 5, 6, 7 — start included, stop excluded (half-open).
How do you get both index and value while looping?
for i, v in enumerate(seq):
What does zip(a, b) stop at?
The end of the shorter sequence.
Why is modifying a list while iterating it dangerous?
The iterator tracks a position index; removing/inserting shifts items so the cursor skips or repeats elements.
Iterating a dict with for k in d: gives you what?
The keys (use .values() / .items() otherwise).
After for i in range(3): pass, what is i?
2 — the loop variable leaks out and keeps its last value.
What's the safe way to filter a list while "looping"?
Build a new list, e.g. comprehension [x for x in xs if cond], or iterate a copy xs[:].

Connections

  • while loop — condition-based repetitionfor is built from while + iter/next.
  • range function — the standard numeric iterable for counting loops.
  • Lists and indexing — the most common sequence you iterate.
  • Strings as sequences — why looping a string yields characters.
  • Dictionaries — keys, values, items — what for yields from a dict.
  • List comprehensions — a compact loop that builds a new list.
  • enumerate and zip — pairing indices/sequences cleanly.
  • Iterators and generators — the deeper protocol powering every for.

Concept Map

iterates over

examples

binds current item to

each pass is

desugars to

step 1 calls

produces

remembers position

step 3 calls

when exhausted raises

triggers

preferred over

for loop

iterable

list str tuple range dict

loop variable

iteration

while loop equivalent

iter(seq)

iterator

cursor moves forward

next(...)

StopIteration

break, loop ends cleanly

manual index counting

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Socho tumhare paas ek list ya string hai — yaani items ka ek dabba. for loop ka kaam simple hai: har item ko ek-ek karke uthao aur uspe kuch karo, jab tak items khatam na ho jaayein. Tumhe ginti khud nahi karni padti ki kitne items hain; Python khud dekh leta hai. Yahi cheez for fruit in fruits: likhne par hoti hai — fruit ko bari-bari se har element mil jaata hai.

Andar ka mechanism samjho: Python pehle iter(sequence) se ek cursor banata hai, phir next() baar-baar call karke agla item deta jaata hai. Jab koi item nahi bachta to StopIteration aata hai aur loop ruk jaata hai. Iska matlab for actually ek while True + try/except ka chhota roop hai. Isliye index ki tension nahi hoti — yahi for ka asli faayda hai.

Kuch dhyaan rakhne wali baatein: range(1, 5) matlab 1,2,3,4stop excluded hota hai (start andar, stop bahar). List ke upar loop karte waqt usi list ko mat badlo (remove/add), warna cursor item skip kar deta hai; copy lo ya nayi list banao. Dict ke upar loop karoge to keys milengi, values chahiye to .values() ya .items() use karo. Index ke saath value chahiye to enumerate, do list saath chahiye to zip — yeh Pythonic tarika hai.

Go deeper — visual, from zero

Test yourself — Introduction to Programming (Python)

Connections