Python For Loop
Iterating Over Sequences: Understanding the For Loop
In Python, the for loop is used to iterate over a sequence (like a list, tuple, string, or range) or other iterable objects. It's a fundamental tool for repeating a block of code once for each item in a collection.
Unlike the while
loop, which repeats as long as a condition is true, the for
loop is designed for situations where you want to perform an action for every item in a known sequence.
What Is a For Loop?
A for loop allows you to execute a block of code repeatedly for each item in an iterable. An iterable is any Python object that can return its members one at a time – examples include lists, tuples, strings, and the result of the range()
function.
When the loop runs, a variable is temporarily assigned to each item in the iterable in sequence, and the code block inside the loop is executed with that item.
Syntax of the For Loop
The basic syntax of a for
loop looks like this:
for item in iterable:
# code block to be executed for each item
for
: The keyword that starts a for loop.item
: A variable name you choose. In each iteration of the loop, this variable will hold the current item from the iterable.in
: A keyword used to specify the iterable you want to loop over.iterable
: The sequence or collection (like a list, string, or the result ofrange()
) that the loop will go through.:
: Marks the end of thefor
statement header.- Indented Code Block: The code that runs for each item. It must be indented.
Iterating Over a List
A very common use of the for
loop is to go through each element in a list.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
In this example, the variable fruit
takes on the value "apple"
, then "banana"
, then "cherry"
, and the print()
function is called for each of those values.
Iterating Over a String
Strings are sequences of characters, so you can iterate over them character by character using a for
loop.
message = "Python"
for char in message:
print(char)
Output:
P
y
t
h
o
n
The variable char
holds each character of the string in turn.
Iterating Using range()
The range()
function is often used with for
loops to perform an action a specific number of times. It generates a sequence of numbers.
range(stop)
: Generates numbers from 0 up to (but not including)stop
.range(start, stop)
: Generates numbers fromstart
up to (but not including)stop
.range(start, stop, step)
: Generates numbers fromstart
up to (but not including)stop
, incrementing bystep
.
Example 1: range(stop)
for i in range(5):
print(i)
Output:
0
1
2
3
4
The loop runs 5 times, with i
taking values from 0 to 4.
Example 2: range(start, stop)
for i in range(2, 6):
print(i)
Output:
2
3
4
5
The loop starts with i = 2
and goes up to (but not including) 6.
Example 3: range(start, stop, step)
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
The loop starts at 1, goes up to (but not including) 10, and increments by 2 each time.
Using break
and continue
Just like with while
loops, you can control the flow of a for
loop using break
and continue
.
break
: Exits the loop immediately.continue
: Skips the rest of the current iteration and moves to the next item in the sequence.
Example with break
:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in numbers:
if number == 5:
print("Found 5, stopping the loop.")
break
print(f"Processing {number}")
Output:
Processing 1
Processing 2
Processing 3
Processing 4
Found 5, stopping the loop.
The loop stops as soon as number
becomes 5.
Example with continue
:
for i in range(1, 6):
if i == 3:
print("Skipping 3")
continue
print(f"Processing {i}")
Output:
Processing 1
Processing 2
Skipping 3
Processing 4
Processing 5
When i
is 3, the continue
statement is hit, and the print(f"Processing {i}")
line is skipped for that iteration. The loop then moves to the next value (4).
The else
Clause with For Loops
A for
loop can optionally have an else
block. The code inside the else
block is executed only if the loop completes without encountering a break
statement.
Example where else
runs:
items = [1, 2, 3]
for item in items:
print(item)
else:
print("Loop finished without breaking.")
Output:
1
2
3
Loop finished without breaking.
The loop went through all items, so the else
block ran.
Example where else
does NOT run:
items = [1, 2, 3, 4, 5]
for item in items:
if item == 3:
print("Found 3, breaking loop.")
break
print(item)
else:
print("Loop finished without breaking.")
Output:
1
2
Found 3, breaking loop.
The loop was stopped by break
, so the else
block was skipped.
Iterating with Index and Value (enumerate()
)
Sometimes you need to access both the index (position) and the value of an item while looping through a sequence. The enumerate()
function is perfect for this. It wraps an iterable and returns pairs of (index, value)
for each item.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
Output:
Index 0: apple
Index 1: banana
Index 2: cherry
enumerate()
makes it easy to get both pieces of information in each iteration.
Iterating Over Dictionaries
You can iterate over dictionaries in several ways using for
loops:
-
Iterating over Keys (Default):
user_data = {"name": "Alice", "age": 30, "city": "New York"} print("Iterating over keys:") for key in user_data: # By default, loops over keys print(key)
Output:
Iterating over keys: name age city
-
Iterating over Values: Use the
.values()
method.user_data = {"name": "Alice", "age": 30, "city": "New York"} print("Iterating over values:") for value in user_data.values(): print(value)
Output:
Iterating over values: Alice 30 New York
-
Iterating over Items (Key-Value Pairs): Use the
.items()
method. This returns tuples of(key, value)
.user_data = {"name": "Alice", "age": 30, "city": "New York"} print("Iterating over items:") for key, value in user_data.items(): # Unpack the (key, value) tuple print(f"{key}: {value}")
Output:
Iterating over items: name: Alice age: 30 city: New York
Nested For Loops
You can place one for
loop inside another. This is called a nested loop. The inner loop will complete all of its iterations for each single iteration of the outer loop.
for i in range(3): # Outer loop
print(f"Outer loop iteration {i}")
for j in range(2): # Inner loop
print(f" Inner loop iteration {j}")
Output:
Outer loop iteration 0
Inner loop iteration 0
Inner loop iteration 1
Outer loop iteration 1
Inner loop iteration 0
Inner loop iteration 1
Outer loop iteration 2
Inner loop iteration 0
Inner loop iteration 1
Understanding nested loops is important for working with multi-dimensional data structures like lists of lists or for tasks requiring combinations.
Summary
- The
for
loop iterates over sequences and other iterables. - It executes a code block once for each item in the iterable.
- Use
range()
to loop a specific number of times. - Use
break
to exit the loop early. - Use
continue
to skip the current iteration. - The
else
block runs if the loop completes normally (withoutbreak
). enumerate()
provides both the index and the value.- You can iterate over dictionary keys, values, or items.
- Nested loops involve one loop inside another for complex iterations.
The for
loop is a powerful and frequently used construct in Python for processing collections of data.