Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
for Loops
for loops iterate over sequences (lists, strings, ranges). They're the most common loop in Python. Use them when you know how many times to repeat or when iterating over a collection.
for Loop Syntax
# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterate over a string
for char in "Python":
print(char, end=" ") # P y t h o n
print()
# Iterate over a range
for i in range(5):
print(i, end=" ") # 0 1 2 3 4
print()
# Range with start, stop, step
for i in range(1, 11):
print(i, end=" ") # 1 2 3 4 5 6 7 8 9 10
print()
for i in range(0, 20, 2):
print(i, end=" ") # 0 2 4 6 8 10 12 14 16 18
print()
# Enumerate - get index AND value
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(f"{index}: {color}")Try It Yourself: Multiplication Table
Tip
Tip
Use enumerate() instead of range(len(list)). for i, item in enumerate(fruits): is more Pythonic.
for loops for known counts, while loops until a condition is met
Common Mistake
Warning
Modifying a list while iterating over it causes skipped items. Never do for item in list: list.remove(item). Iterate over a copy instead.
Practice Task
Note
(1) Print a multiplication table for 7. (2) Sum 1 to 100 using a for loop. (3) Count vowels in a string. (4) Use enumerate to print index:value pairs.