for Loop (Iteration)
The for loop iterates over items of any iterable (string, list, tuple, dict, range, set) — unlike C's counter-based for loop.
Syntax
for item in iterable:
statement(s)
for ch in "Python":
print(ch)
Output:
P
y
t
h
o
n
Using range()
range(start, stop, step) generates a sequence of numbers (stop is excluded).
for i in range(5): # 0,1,2,3,4
print(i)
for i in range(1, 6): # 1,2,3,4,5
print(i)
for i in range(10, 0, -2): # 10,8,6,4,2
print(i)
Iterating over a list
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)
Iterating with index — enumerate()
for index, fruit in enumerate(fruits):
print(index, fruit)
# 0 apple
# 1 banana
# 2 mango
Iterating over a dictionary
student = {"name": "Riya", "age": 21}
for key in student:
print(key, ":", student[key])
for key, value in student.items():
print(key, "->", value)
for-else
The else block runs only if the loop completes without a break.
for i in range(5):
print(i)
else:
print("Loop finished normally")