๐
For loops
Iterate over sequences
Reward
+60 XP
Looping with range
range(n) yields 0, 1, ..., n-1. for x in range(n) runs the body n times.
for i in range(5):
print(i)Looping over lists
for can iterate any sequence: lists, strings, tuples.
for fruit in ["apple", "pear", "kiwi"]:
print(fruit)enumerate
enumerate gives you the index alongside each value.
for i, fruit in enumerate(["apple", "pear"]):
print(i, fruit)Try it yourself
Run the example below. Edit it and see what changes.
main.py
Output
Press Run to execute (Ctrl/Cmd+Enter)
Common mistakes
- โ Forgetting range goes up to but not including the end value.
- โ Missing the colon after the for line.
- โ Modifying a list while iterating over it.
