Last updated: Apr 10, 2024
Reading timeยท5 min
To use multiple variables in a for
loop:
zip
function to group multiple iterables into tuples.for
loop to iterate over the zip
object.list1 = ['bobby', 'hadz', 'com'] list2 = [1, 2, 3] list3 = ['a', 'b', 'c'] for item1, item2, item3 in zip(list1, list2, list3): # bobby 1 a # hadz 2 b # com 3 c print(item1, item2, item3)
The zip() function iterates over several iterables in parallel and produces tuples with an item from each iterable.
The zip
function returns an iterator of tuples.
list1 = ['bobby', 'hadz', 'com'] list2 = [1, 2, 3] list3 = ['a', 'b', 'c'] # ๐๏ธ [('bobby', 1, 'a'), ('hadz', 2, 'b'), ('com', 3, 'c')] print(list(zip(list1, list2, list3)))
0
, the second tuple consists of the elements in each list that have an index of 1
, etc.Make sure to declare exactly as many variables as there are items in each tuple.
list1 = ['bobby', 'hadz', 'com'] list2 = [1, 2, 3] # ๐๏ธ [('bobby', 1), ('hadz', 2), ('com', 3)] print(list(zip(list1, list2))) for item1, item2 in zip(list1, list2): # bobby 1 # hadz 2 # com 3 print(item1, item2)
If you try to unpack more or fewer variables than there are items in each tuple, you'd get an error.
for
loop when iterating over two-dimensional lists, lists of tuples, etc.Here is an example of
unpacking variables in a
for
loop when iterating over a two-dimensional list.
two_dimensional_list = [ ['bobby', 1], ['hadz', 2], ['com', 3] ] for first, second in two_dimensional_list: # bobby 1 # hadz 2 # com 3 print(first, second)
The first
variable gets assigned the first element of the nested list of the
current iteration and the second
variable gets assigned the second element.
When you use unpacking, you have to make sure to unpack exactly as many variables as there are values in the iterable, otherwise an error is raised.
Here is an example that doesn't unpack the values of each tuple.
list1 = ['bobby', 'hadz', 'com'] list2 = [1, 2, 3] for tup in zip(list1, list2): # bobby 1 # hadz 2 # com 3 print(tup[0], tup[1])
If not all nested sequences have the same length, access each sequence at an index.
list_of_lists = [ ['bobby', 1, 'a'], ['hadz', 2, 'b'], ['com', 3, 'c', 'xyz', 123] ] for sublist in list_of_lists: # bobby 1 a # hadz 2 b # com 3 c print(sublist[0], sublist[1], sublist[2])
The last sublist has more items than the previous two, so unpacking is not an option.
If you need to iterate over the key-value pairs of a dictionary in a for
loop,
use the dict.items()
method.
This is a three-step process:
dict.items()
method to get a view of the dictionary's items.for
loop to iterate over the view object.my_dict = { 'first': 'bobby', 'last': 'hadz', 'age': 30 } for key, value in my_dict.items(): # first bobby # last hadz # age 30 print(key, value)
The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).
my_dict = { 'first': 'bobby', 'last': 'hadz', 'age': 30 } # ๐๏ธ dict_items([('first', 'bobby'), ('last', 'hadz'), ('age', 30)]) print(my_dict.items())
On each iteration of the for
loop, we unpack the current key and value into
variables.
If you need to get access to the index of the current iteration in a for
loop,
use the enumerate()
function.
This is a three-step process:
enumerate()
function to get access to the current index.for
loop to iterate over the enumerate
objecta_list = ['bobby', 'hadz', '.com'] for index, item in enumerate(a_list): # bobby 0 # hadz 1 # .com 2 print(item, index)
The enumerate() function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the corresponding item.
a_list = ['bobby', 'hadz', '.com'] # ๐๏ธ [(0, 'bobby'), (1, 'hadz'), (2, '.com')] print(list(enumerate(a_list)))
On each iteration of the for
loop, we unpack the current index and item into
variables.
If you need to use 2 variables in a for
loop to simulate a nested for
loop,
use the itertools.product()
class.
from itertools import product list_1 = ['bobby', 'hadz', 'com'] list_2 = [1, 2, 3] # bobby 1 # bobby 2 # bobby 3 # hadz 1 # hadz 2 # hadz 3 # com 1 # com 2 # com 3 for item_1, item_2 in product(list_1, list_2): print(item_1, item_2)
The
itertools.product()
method is roughly equivalent to a nested for
loop.
For each item in list_1
, the for
loop iterates over each item in list_2
.
Here is an example of a nested for
loop that achieves the same result.
list_1 = ['bobby', 'hadz', 'com'] list_2 = [1, 2, 3] # bobby 1 # bobby 2 # bobby 3 # hadz 1 # hadz 2 # hadz 3 # com 1 # com 2 # com 3 for item_1 in list_1: for item_2 in list_2: print(item_1, item_2)
You can learn more about the related topics by checking out the following tutorials: