Python provides several ways to iterate over collections like lists, tuples, dictionaries, and other iterable objects. While it doesn’t have a direct equivalent to a "foreach" loop found in some other languages, the core for
loop in Python serves the same purpose – allowing you to process each item in a collection sequentially.
Basic Iteration with for
Loops
The most common and Pythonic way to iterate is using the for
loop. It’s designed to work directly with iterable objects, eliminating the need for index-based access in many cases.
pets = ['cat', 'dog', 'fish']
for pet in pets:
print(pet)
In this example, the for
loop iterates through each element in the pets
list. In each iteration, the current element is assigned to the variable pet
, which you can then use within the loop’s body.
Iterating with Indices using range()
and len()
Sometimes, you might need to access the index of the current item while iterating. You can achieve this using the range()
and len()
functions.
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
print(i, a[i])
len(a)
returns the number of elements in the list a
. range(len(a))
generates a sequence of numbers from 0 up to (but not including) the length of the list. In each iteration, i
represents the current index, allowing you to access the element at that index using a[i]
.
Using enumerate()
for Index and Value
Python provides a more elegant way to iterate with both index and value using the enumerate()
function.
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
enumerate()
takes an iterable as input and returns a sequence of tuples, where each tuple contains the index and the corresponding value. This eliminates the need to manually manage the index variable.
Iterating Over Dictionaries
When working with dictionaries, you often need to access both the keys and the values. The .items()
method is specifically designed for this purpose.
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
for key, value in my_dict.items():
print(key, value)
.items()
returns a view object that displays a list of a dictionary’s key-value tuple pairs. The for
loop unpacks each tuple into the key
and value
variables, allowing you to access them within the loop.
Creating a forEach
Function (Optional)
While the built-in for
loop is sufficient for most iteration tasks, you can define your own forEach
function for stylistic preference or to mimic functionality from other languages:
def forEach(list, function):
for i, v in enumerate(list):
function(v, i, list)
This custom function takes a list and a function as input. It iterates through the list, and for each element, it calls the provided function with the element’s value, index, and the original list as arguments. This offers a more functional programming style, but it’s generally not necessary given Python’s expressive for
loop.
In most cases, the standard for
loop, along with techniques like enumerate()
and the .items()
method, provide the most Pythonic and efficient ways to iterate over collections.