Loading lessons...
For Loops
For Loops
A for loop in Python iterates over a sequence, not by counting.
Loop over a list
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Loop over a string
for x in "banana":
print(x) # b, a, n, a, n, a
Loop over a range
range() produces a sequence of numbers:
for x in range(6):
print(x) # 0, 1, 2, 3, 4, 5
Range with start and end
for x in range(2, 6):
print(x) # 2, 3, 4, 5
Range with a step
for x in range(2, 30, 3):
print(x) # 2, 5, 8, 11, ...
break and continue
They work the same as in while loops:
for x in fruits:
if x == "banana":
break
print(x) # apple only
for x in fruits:
if x == "banana":
continue
print(x) # skips banana
else on a for loop
Runs after the loop finishes, unless break stopped it:
for x in range(3):
print(x)
else:
print("Loop finished!")
Nested loops
adj = ["red", "big"]
fruits = ["apple", "banana"]
for a in adj:
for f in fruits:
print(a, f)
TL;DR
for x in sequence:iterates items, not indexes.range()makes number sequences (start, end, step).- break exits; continue skips; else runs on natural end.
- Loops nest inside each other.