The for
loop is a fundamental programming construct in Python, enabling you to iterate over a sequence (like a list, tuple, string, or range) or other iterable objects. It’s incredibly versatile and forms the backbone of many Python programs. This guide will walk you through its various applications with clear explanations and code examples.
Iterating Through Lists
The simplest use case involves iterating through the elements of a list. Each element is assigned to a variable (in this case, item
) during each iteration.
= ["apple", "banana", "cherry"]
my_list
for item in my_list:
print(item)
This will output:
apple
banana
cherry
Iterating Through Strings
Strings are also iterable sequences of characters. You can use a for
loop to process each character individually.
= "Python"
my_string
for char in my_string:
print(char.upper())
This will output:
P
Y
T
H
O
N
Using Range for Numerical Iteration
The range()
function is often used with for
loops to iterate a specific number of times.
for i in range(5): # Iterates from 0 to 4
print(i)
This outputs:
0
1
2
3
4
You can also specify a starting value and step size:
for i in range(1, 11, 2): # Starts at 1, goes up to (but not including) 11, with a step of 2
print(i)
This will print:
1
3
5
7
9
Iterating Through Dictionaries
While you can iterate directly through the keys of a dictionary:
= {"name": "Alice", "age": 30, "city": "New York"}
my_dict
for key in my_dict:
print(key)
(Output: name
, age
, city
)
You can also access both keys and values using the .items()
method:
for key, value in my_dict.items():
print(f"{key}: {value}")
This outputs:
name: Alice
age: 30
city: New York
Nested For Loops
For loops can be nested to iterate over multiple sequences. This is useful for tasks like processing two-dimensional data (e.g., matrices).
= [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix
for row in matrix:
for item in row:
print(item)
This will print each element of the matrix sequentially.
Loop Control Statements: break
and continue
break
: Terminates the loop prematurely.continue
: Skips the rest of the current iteration and proceeds to the next.
for i in range(10):
if i == 5:
break # Stops the loop when i is 5
print(i)
print("\n---\n")
for i in range(10):
if i == 5:
continue # Skips printing 5
print(i)
These examples demonstrate the core functionality of the Python for
loop. Understanding these concepts is important for writing efficient and readable Python code. Many more advanced applications build upon these fundamental techniques.