In Python, a for loop is used to iterate over a sequence such as a list, tuple, string, or a range of numbers. For each item in the sequence, the loop body is executed once with the loop variable set to that item.
For loops are essential for tasks like processing collections of data, repeating actions a fixed number of times, and working with multi-dimensional structures using nested loops.
range(): A built-in function that generates a sequence of numbers.for-else: An optional else block that runs when the loop finishes normally (no break).General syntax of a Python for loop:
for variable in iterable:
# loop body
# code that uses "variable"
On each iteration, variable receives the next item from iterable, and the loop body is executed. When there are no items left, the loop stops and execution continues after the loop.
A for loop iterating over a list of fruits:
# define a list of fruits
fruits = ["apple", "banana", "cherry"]
# loop through each fruit and print it
for fruit in fruits:
print(fruit)
Looping through a sequence of numbers using range():
for i in range(5):
print(i) # prints 0, 1, 2, 3, 4
A for loop inside another for loop:
# outer loop runs 3 times
for i in range(3):
# inner loop runs 2 times for each i
for j in range(2):
print(f"i={i}, j={j}")
The else block runs only if the loop completes all iterations without hitting a break statement.
# loop from 0 to 2
for i in range(3):
print(i)
# runs because the loop finished without a break
else:
print("Loop finished without break")
apple banana cherry
range(5) loop:0 1 2 3 4
(i, j) where i is 0–2 and j is 0–1, e.g. i=0, j=0, i=0, j=1, …, i=2, j=1.for-else loop: prints 0, 1, 2, and then "Loop finished without break" because the loop completes normally.for loops when iterating over sequences (lists, strings, ranges, etc.).range(start, stop, step) to generate numeric sequences.else block can be used to run code if the loop completes without a break.: at the end of the for line.range() boundaries to avoid off-by-one errors (remember it stops before the stop value).1 to 10.1–3.for-else loop to check if a number exists in a list. If not found, print a message like "Number not found".