for loop — iterating over sequences
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
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?
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?
StopIteration, which the loop catches as a break.What does range(2, 8) produce?
How do you get both index and value while looping?
for i, v in enumerate(seq):What does zip(a, b) stop at?
Why is modifying a list while iterating it dangerous?
Iterating a dict with for k in d: gives you what?
.values() / .items() otherwise).After for i in range(3): pass, what is i?
What's the safe way to filter a list while "looping"?
[x for x in xs if cond], or iterate a copy xs[:].Connections
- while loop — condition-based repetition —
foris built fromwhile+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
foryields 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
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,4 — stop 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.