How to Use Multiple Variables in Python for
Loops
Python's for
loops are incredibly versatile.
This guide explores how to effectively use multiple variables within for
loops, covering techniques like tuple unpacking, iterating over dictionaries, using enumerate()
for index access, and simulating nested loops with itertools.product()
.
Unpacking Iterables with Multiple Variables
The most common way to use multiple variables in a for
loop is by unpacking elements from an iterable (like a list or tuple) directly into variables within the loop header.
my_list = [('tutorial', 1), ('reference', 2), ('com', 3)]
for item1, item2 in my_list: # item1 iterates over all first elements in tuples,
# and item2 will iterate over all second elements in the tuples
print(item1, item2)
Output:
tutorial 1
reference 2
com 3
You can also use the zip()
function, to achieve the same result.
list1 = ['tutorial', 'reference', 'com']
list2 = [1, 2, 3]
list3 = ['a', 'b', 'c']
for item1, item2, item3 in zip(list1, list2, list3):
print(item1, item2, item3)
Output
tutorial 1 a
reference 2 b
com 3 c
- In this case the
zip()
function iterates over multiple iterables in parallel.
Lists of Tuples
This is particularly useful when your list contains tuples:
list_of_tuples = [('tutorial', 1), ('reference', 2), ('com', 3)]
for name, number in list_of_tuples:
print(name, number)
Output:
tutorial 1
reference 2
com 3
- Each tuple in
list_of_tuples
is unpacked into thename
andnumber
variables during each iteration.
Two-Dimensional Lists (Lists of Lists)
You can also unpack elements from nested lists:
two_dimensional_list = [
['tutorial', 1],
['reference', 2],
['com', 3]
]
for first, second in two_dimensional_list:
print(first, second)
Output:
tutorial 1
reference 2
com 3
The Importance of Matching Lengths
The number of variables in the for
loop header must match the number of elements in each item you're unpacking. If they don't match, you'll get a ValueError
.
If the nested lists/tuples don't have the same size you can access their elements by using indexing:
list_of_lists = [
['tutorial', 1, 'a'],
['reference', 2, 'b'],
['com', 3, 'c', 'xyz', 123] # Different length
]
for sublist in list_of_lists:
print(sublist[0], sublist[1], sublist[2]) # Access by index
Output:
tutorial 1 a
reference 2 b
com 3 c
- This is the most reliable way to access the variables without unpacking them.
Iterating Over Dictionaries with dict.items()
To iterate over both the keys and values of a dictionary simultaneously, use the items()
method:
my_dict = {
'first': 'tutorial',
'last': 'reference',
'age': 30
}
for key, value in my_dict.items():
print(key, value)
Output
first tutorial
last reference
age 30
my_dict.items()
returns a view object that yields key-value pairs as tuples.- These tuples are then unpacked into the
key
andvalue
variables in the loop.
Using enumerate()
for Index and Value
The enumerate()
function adds a counter to an iterable, making it easy to access both the index and value during iteration:
a_list = ['tutorial', 'reference', '.com']
for index, item in enumerate(a_list):
print(item, index) # Access both item and its index
Output:
tutorial 0
reference 1
.com 2
enumerate(a_list)
returns an iterator that yields pairs of(index, item)
.- You can unpack these pairs directly in the
for
loop. - You can also specify the
start
parameter, to set the starting value of the counter.
Simulating Nested Loops with itertools.product()
The itertools.product()
function provides a concise way to generate the Cartesian product of multiple iterables, effectively simulating nested loops:
from itertools import product
list_1 = ['tutorial', 'reference', 'com']
list_2 = [1, 2, 3]
for item_1, item_2 in product(list_1, list_2):
print(item_1, item_2)
Output:
tutorial 1
tutorial 2
tutorial 3
reference 1
reference 2
reference 3
com 1
com 2
com 3
itertools.product()
iterates through all possible combinations of items in the list.- This avoids deeply nested
for
loops and can be more readable.