In Python, the for loop is an iterator-based loop that steps through items of any iterable sequence (such as a list, string, tuple, dictionary, or generator) one by one. It eliminates index tracking variables and array bounds errors, making code exceptionally clean and expressive.
# Iterating over a string:
for char in "PYTHON":
print(char, end=" ")
# Output: P Y T H O N
# Iterating over a list:
languages = ["Python", "Rust", "Go", "TypeScript"]
for lang in languages:
print(f"Modern language: {lang}")
range(start, stop, step) FunctionThe range() function produces an immutable sequence of integers on demand without loading all numbers into memory at once:
# 1. Single argument: range(stop) -> 0 to stop-1
for i in range(5):
print(i, end=" ") # 0 1 2 3 4
# 2. Two arguments: range(start, stop)
for i in range(10, 15):
print(i, end=" ") # 10 11 12 13 14
# 3. Three arguments: range(start, stop, step)
for i in range(10, 30, 5):
print(i, end=" ") # 10 15 20 25
# 4. Counting backwards with negative step:
for i in range(5, 0, -1):
print(i, end=" ") # 5 4 3 2 1
enumerate() and zip()enumerate(iterable, start): Loop with Index & Valuetoppers = ["Priya", "Rahul", "Ananya"]
for rank, name in enumerate(toppers, start=1):
print(f"Rank #{rank}: {name}")
# Rank #1: Priya
# Rank #2: Rahul
# Rank #3: Ananya
zip(*iterables): Loop Over Multiple Lists in Parallelstudents = ["Aman", "Rhea", "Vikram"]
marks = [92, 88, 95]
for name, score in zip(students, marks):
print(f"{name} scored {score}/100")
for...else BlockLike the while loop, an else block attached to a for loop executes only if the loop completes all iterations without encountering a break:
# Prime Number Checker using for-else:
num = 29
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
print(f"{num} is composite (divisible by {i}).")
break
else:
print(f"{num} is a PRIME number!")
stop boundary is strictly exclusive. range(1, 10) yields numbers from 1 up to 9.