For loops iterate over sequences (lists, strings, ranges, etc.).
For Loops
A for loop iterates over a sequence (list, tuple, string, range) and executes a block of code for each item.
range() Function
Generates a sequence of numbers: range(start, stop, step)
enumerate()
Returns index-value pairs while iterating.
zip()
Iterates over multiple sequences simultaneously.
Syntax
<pre><code># Loop over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Loop with range
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# range with start and stop
for i in range(1, 6):
print(i) # 1, 2, 3, 4, 5
# range with step
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
# Loop over string
for char in "Python":
print(char)
# enumerate (index + value)
for index, value in enumerate(fruits):
print(f"{index}: {value}")
# zip (parallel iteration)
names = ["Alice", "Bob"]
scores = [95, 87]
for name, score in zip(names, scores):
print(f"{name}: {score}")
</code></pre>
Revision Notes
• for x in iterable: iterates each element
• range(n) = 0 to n-1
• range(start, stop, step)
• enumerate() gives index + value
• zip() iterates multiple lists together