For Loops
The for loop is Python's workhorse for iteration. Unlike traditional
counter-based loops in C or Java, Python's for loop iterates directly over items in a sequence -
making it elegant, readable, and powerful!
Iterating Over Sequences
Python's for loop works with any iterable: lists, strings, tuples, sets, dictionaries, and more. The loop variable takes each value in the sequence, one at a time.
Click Run to execute your code
for (int i = 0; i < n; i++). In Python, you simply write
for item in collection:. This is called "iterating over" a sequence
rather than "counting up to" a number.
The range() Function
When you need to repeat something a specific number of times or need numeric sequences,
use range(). It generates numbers on-demand without creating a full list in memory.
| Syntax | Description | Example Output |
|---|---|---|
range(5) | 0 to 4 (stop-1) | 0, 1, 2, 3, 4 |
range(2, 6) | 2 to 5 (start to stop-1) | 2, 3, 4, 5 |
range(0, 10, 2) | 0 to 8, step by 2 | 0, 2, 4, 6, 8 |
range(5, 0, -1) | 5 to 1, counting down | 5, 4, 3, 2, 1 |
Click Run to execute your code
range() doesn't create a list in memory -
it generates numbers one at a time. This means range(1000000) uses minimal memory,
unlike list(range(1000000)) which would create a million-item list!
Using enumerate()
When you need both the index and the value while iterating, enumerate() is your
friend. It's cleaner than maintaining a manual counter!
Click Run to execute your code
enumerate(items, start=1) when you want
human-friendly numbering starting from 1 instead of 0. Perfect for menus and lists!
Practical Examples
For loops are essential for processing data, building new collections, and combining information from multiple sources.
Click Run to execute your code
for item in list.copy():
Common Mistakes
1. Off-by-one errors with range()
# Wrong - this prints 0-9, not 1-10!
for i in range(10):
print(i)
# Correct - for 1-10
for i in range(1, 11): # stop is exclusive!
print(i)
2. Using range(len()) when not needed
# Unnecessary - don't do this!
for i in range(len(fruits)):
print(fruits[i])
# Better - iterate directly
for fruit in fruits:
print(fruit)
# If you need the index too, use enumerate
for i, fruit in enumerate(fruits):
print(i, fruit)
3. Modifying list while iterating
# Wrong - unpredictable behavior!
for item in items:
if some_condition:
items.remove(item) # Don't do this!
# Correct - iterate over a copy
for item in items.copy():
if some_condition:
items.remove(item)
4. Forgetting the colon
# Wrong - SyntaxError!
for item in items
print(item)
# Correct
for item in items:
print(item)
Exercise: Sum Calculator
Task: Calculate sums using for loops.
Requirements:
- Calculate the sum of the
numberslist - Calculate the sum of numbers from 1 to 100 using
range()
Click Run to execute your code
Show Solution
numbers = [10, 20, 30, 40, 50]
total_sum = 0
# 1. Sum of list
for num in numbers:
total_sum += num
print(f"Sum of list: {total_sum}") # 150
# 2. Sum of 1-100
range_sum = 0
for i in range(1, 101): # 101 because stop is exclusive
range_sum += i
print(f"Sum of 1-100: {range_sum}") # 5050
Summary
- for item in sequence: Iterates over each item directly
- range(stop): Generates 0 to stop-1
- range(start, stop, step): Full control over the sequence
- enumerate(): Get both index and value
- zip(): Iterate over multiple sequences in parallel
- dict.items(): Iterate over dictionary key-value pairs
- Don't modify lists while iterating over them
What's Next?
Now that you can iterate with for loops, let's learn about while loops - loops that continue as long as a condition is true. While loops are perfect when you don't know in advance how many iterations you need!
Enjoying these tutorials?