Part of Python for Beginners

Learn Python Loops in 6 Minutes - for, while, range(), enumerate() | Tutorial #7

Sandy LaneSandy Lane

Video: Learn Python Loops in 6 Minutes - for, while, range(), enumerate() | Tutorial #7 by Taught by Celeste AI - AI Coding Coach

Take the quiz on the full lesson page
Test what you've read · interactive walkthrough

Python Loops: for, while, range, enumerate

for x in iterable: for iteration. range(stop) for counted loops. while cond: for "until done." break and continue for control. enumerate to get the index along with the value.

Python's loops are simpler than C's — no init/test/step header. The for loop iterates any iterable (lists, strings, files, generators).

for with range

for i in range(1, 6):
  print(f"Count: {i}")
# Count: 1
# Count: 2
# ...
# Count: 5

range(start, stop) is start through stop - 1 (exclusive upper bound). For 1-5 inclusive, use range(1, 6).

for i in range(5):       # 0, 1, 2, 3, 4 (default start = 0)
for i in range(1, 11):    # 1 through 10
for i in range(0, 21, 2): # 0, 2, 4, ..., 20 (step 2)
for i in range(10, 0, -1): # 10, 9, ..., 1 (descending)

range(start, stop, step) is the full form.

for over a list

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
  print(fruit)

No index needed — Python iterates the items directly. Compare to C-style for (int i = 0; i < n; i++) print(arr[i]);.

For both index and value, use enumerate:

for i, fruit in enumerate(fruits):
  print(f"{i}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry

enumerate(seq) yields (index, value) pairs. Pythonic; idiomatic.

while

count = 5
while count > 0:
  print(f"Countdown: {count}")
  count = count - 1

while cond: runs the body while the condition is truthy. Same as C, but with indentation instead of braces.

while True: for "loop forever":

while True:
  num = num + 1
  if num == 5:
    print("Breaking at 5!")
    break

break exits the loop. continue skips to the next iteration.

break and continue

i = 0
while i < 10:
  i = i + 1
  if i % 2 != 0:
    continue   # skip odd numbers
  print(f"Even: {i}")

continue goes back to the top of the loop. break exits entirely.

For the same in for:

for i in range(10):
  if i % 2 != 0:
    continue
  print(f"Even: {i}")

else on a loop

for i in range(5):
  if i == 99:
    break
else:
  print("Loop finished without break")

A loop's else runs if the loop completed without a break. Useful for "search for X; if not found, do Y":

for x in items:
  if x.matches(criteria):
    do_something(x)
    break
else:
  print("No match found")

Counterintuitive name — else here means "no break."

Iterating a string

for char in "hello":
  print(char)
# h
# e
# l
# l
# o

Strings are iterables — characters one at a time.

Iterating a dict

ages = {"Alice": 30, "Bob": 25}

for name in ages:                     # default: iterate keys
  print(name)

for name, age in ages.items():        # both
  print(f"{name}: {age}")

for age in ages.values():             # just values
  print(age)

.items(), .keys(), .values(). Iterate with what you need.

Iterating a file

with open("file.txt") as f:
  for line in f:
    print(line.strip())

File objects are iterable — yields lines. The with statement (lesson 25) handles closing.

list comprehensions (preview)

squares = [i * i for i in range(10)]
print(squares)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Compact "transform every element" loop. Lesson 14 covers comprehensions properly.

while else

n = 10
while n > 0:
  if n == 5:
    break
  n -= 1
else:
  print("Reached 0 without break")

Same as for...elseelse runs only if the while completed normally (no break).

Rare in practice; useful for "search until found" patterns.

zip for parallel iteration

names = ["Alice", "Bob", "Charlie"]
scores = [90, 85, 92]
for name, score in zip(names, scores):
  print(f"{name}: {score}")

zip(a, b) yields pairs. Stops at the shorter iterable.

For three or more: zip(a, b, c). For "extend shorter with default," use zip_longest from itertools.

reversed and sorted

for i in reversed(range(5)):
  print(i)   # 4 3 2 1 0

for x in sorted([3, 1, 4, 1, 5]):
  print(x)   # 1 1 3 4 5

for x in sorted(items, key=lambda x: x.priority):
  ...

reversed(seq) yields elements in reverse. sorted(seq) returns a sorted list. sorted(seq, key=fn) sorts by a custom key.

Common stumbles

Modifying a list while iterating. Items skipped or repeated. Iterate a copy: for x in list(my_list):.

Off-by-one in range. range(10) is 0-9. range(1, 10) is 1-9. Always range(0, n) for "n items."

Using index when not needed. for i in range(len(lst)): lst[i] — verbose. Use for x in lst: directly.

Missing colons. Every for/while/if/etc. needs : at the end.

for x in some_dict: returning keys. Default for dict is keys. For values, for v in d.values().

Forgetting break after found. Loop continues after the find — wasted work, possibly wrong logic.

What's next

Lesson 8: lists. Methods (append, pop, sort), slicing, in, copying.

Recap

for x in iterable: iterates any iterable. range(start, stop, step) for counted loops. enumerate(seq) for (index, value) pairs. while cond: for "loop while truthy." break exits, continue skips. for/else runs the else only if no break. zip for parallel iteration. reversed/sorted for transformed iteration. Iterate dicts with .items()/.keys()/.values(). Don't modify a list while iterating it.

Next lesson: lists.

Ready? Take the quiz on the full lesson page →
Test what you've learned. Watch the lesson and try the interactive quiz on the same page.