Python for
Loop Explained with Examples
In Python, the for
loop is used to iterate over a sequence (such as a list, tuple, dictionary, string, or a range of numbers). It's commonly used when you know how many times you want to loop.
Syntax
for variable in sequence:
# block of code
variable
: A temporary name for the current item in the loop.
sequence
: The collection of items to loop over.
Example 1: Looping through a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Example 2: Looping with range()
The range()
function generates a sequence of numbers.
for i in range(5):
print(i)
Output:
0
1
2
3
4
range(5)
means from 0 to 4 (5 is not included).
Example 3: Using range(start, stop, step)
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
Example 4: Looping through a String
for char in "Python":
print(char)
Output:
P
y
t
h
o
n
Example 5: Using for
with else
for i in range(3):
print(i)
else:
print("Loop finished!")
Output:
0
1
2
Loop finished!
Example 6: Nested for
Loops
for i in range(1, 3):
for j in range(1, 4):
print(f"i={i}, j={j}")
Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
Example 7: for
Loop with Dictionary
person = {"name": "Alice", "age": 25}
for key, value in person.items():
print(key, "=", value)
Output:
name = Alice
age = 25