Using multiple variables in a For loop in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
5 min

banner

# Table of Contents

  1. Using multiple variables in a For loop in Python
  2. Declare as many variables as there are items in each tuple
  3. Using multiple variables in a For loop with two-dimensional list
  4. Using multiple variables in a For loop using dict.items()
  5. Using multiple variables in a For loop using enumerate()
  6. Using 2 variables in a For loop to simulate a nested loop

# Using multiple variables in a For loop in Python

To use multiple variables in a for loop:

  1. Use the zip function to group multiple iterables into tuples.
  2. Use a for loop to iterate over the zip object.
  3. Unpack the items of each tuple into variables.
main.py
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)

using multiple variables in for loop

The code for this article is available on GitHub

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.

main.py
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)))
The first tuple in the list consists of the elements in each list with an index of 0, the second tuple consists of the elements in each list that have an index of 1, etc.

# Declare as many variables as there are items in each tuple

Make sure to declare exactly as many variables as there are items in each tuple.

main.py
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)

declare as many variables as there are items in each tuple

The code for this article is available on GitHub

If you try to unpack more or fewer variables than there are items in each tuple, you'd get an error.

You can use this approach to unpack multiple variables in a for loop when iterating over two-dimensional lists, lists of tuples, etc.

# Using multiple variables in a For loop with two-dimensional list

Here is an example of unpacking variables in a for loop when iterating over a two-dimensional list.

main.py
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)

using multiple variables in for loop with two dimensional list

The code for this article is available on GitHub

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.

main.py
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.

main.py
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.

# Using multiple variables in a For loop using dict.items()

This is a three-step process:

  1. Use the dict.items() method to get a view of the dictionary's items.
  2. Use a for loop to iterate over the view object.
  3. Unpack the key and value into variables.
main.py
my_dict = { 'first': 'bobby', 'last': 'hadz', 'age': 30 } for key, value in my_dict.items(): # first bobby # last hadz # age 30 print(key, value)

using multiple variables in for loop using dict items

The code for this article is available on GitHub

The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).

main.py
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.

# Using multiple variables in a For loop using enumerate()

This is a three-step process:

  1. Use the enumerate() function to get access to the current index.
  2. Use a for loop to iterate over the enumerate object
  3. Unpack the current item and index into variables.
main.py
a_list = ['bobby', 'hadz', '.com'] for index, item in enumerate(a_list): # bobby 0 # hadz 1 # .com 2 print(item, index)

using multiple variables in for loop with enumerate

The code for this article is available on GitHub

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.

main.py
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.

# Using 2 variables in a For loop to simulate a nested loop

If you need to use 2 variables in a for loop to simulate a nested for loop, use the itertools.product() class.

main.py
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)

using 2 variables in for loop to simulate nested loop

The code for this article is available on GitHub

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.

main.py
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)

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev