← Back to Blog

for loops — The Full Picture

The idea!

You've covered a lot. for loops, range(), counters, enumerate(), zip().

This is your reference. Everything in one place.

Come back here whenever you need a reminder.

for — the basic loop

Repeats a block once for every item in a sequence.

for letter in "Bull":
    print(letter)

# B
# u
# l
# l

range()

for i in range(5):          # 0 1 2 3 4
for i in range(1, 6):       # 1 2 3 4 5
for i in range(0, 10, 2):   # 0 2 4 6 8
for i in range(5, 0, -1):   # 5 4 3 2 1

Stop is never included. Default start is 0. Default step is 1.

Loop counter

count = 0           # define before

for letter in "Bull":
    count += 1      # update inside

print(count)        # use after — 4

Define before. Update inside. Use after. Works with +=, -=, *=.

enumerate()

for index, letter in enumerate("Bull"):
    print(f"{index}: {letter}")

# 0: B
# 1: u
# 2: l
# 3: l

for index, letter in enumerate("Bull", start=1):
    print(f"{index}: {letter}")   # starts at 1

Position and value — at the same time. No manual counter needed.

zip()

for a, b in zip("Bull", "Horn"):
    print(f"{a} — {b}")

# B — H
# u — o
# l — r
# l — n

Two sequences. One loop. Items matched by position. Stops at the shortest.

range() with len()

word = "Bull"

for i in range(len(word)):
    print(f"Index {i}: {word[i]}")

Gives you indexes to work with — position and character at the same time.

Common Mistakes

  • Every for line ends with :
  • Indentation is syntax — always 4 spaces
  • The loop variable is a copy — modifying it doesn't change the original
  • Define counters before the loop — never inside
  • range(5) starts at 0 — use range(1, 6) for 1 to 5
  • Stop is never included — range(1, 6) gives 1, 2, 3, 4, 5

What you should understand now

  • for iterates over a sequence — one item at a time
  • range() generates numbers — stop, start/stop, or start/stop/step
  • Counters track what happens inside the loop — define before, use after
  • enumerate() gives position and value — no manual counter needed
  • zip() pairs two sequences — items matched by position
[ login to bookmark ] // copied! 32 views · 1 min
// resources
Cheatsheet for loops — The Full Picture
← prev Common FOR Mistakes next → This One's Yours — FOR
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.