Programming is done to solve problems more effectively. Python is no different and aims to solve diverse problems with appropriate solutions. Before understanding how multiple variables can be ingested in a loop, we must first understand why the need of the for loop with multiple variables in python.
Let’s take a look at a few examples to understand more
Here a single list is iterated to display the values.
lst1 = [1,2,3,4,5] for x in lst1: print (x)
But what if we need to simultaneously traverse through multiple lists? The above example has its limitations.
One way is to use a single variable to iterated through multiple lists without having to use various variables
import itertools lst1 = [1,2,3,4,5] lst2=["banana","apple","mango","berry"] lst3=["black","red"] for (a) in zip(lst1, lst2, lst3): print (a)
This can be considered handy if the purpose is only to display the lists or not having much functionality over them individually. But it’s still considered not a good practice to follow this procedure.
Table of Contents
But suppose you want to add functionality to each list separately, that would be a hassle because the list of tuples is returned. for loop with two variables in python is a necessity that needs to be considered.
A solution one might reach is to use a zip method that allows lists to run parallel to each other.
import itertools lst1 = [1,2,3,4,5] lst2=["banana","apple","mango","berry"] lst3=["black","red"] for (a, b, c) in zip(lst1, lst2, lst3): print (a, b, c)
Note how the loop stopped when the shortest list runs out of values. This is due to the default nature of the function to find the shortest list and terminate when all the values are iterated.
You can control that through the longest property of the zip method through for loop’s multiple index.
import itertools lst1 = [1,2,3,4,5] lst2=["banana","apple","mango","berry"] lst3=["black","red"] for (a, b, c) in itertools.zip_longest(lst1, lst2, lst2): print (a, b, c)
multiple variables through a single list
Multiple variables in for loops can have another unique use. iterate through a list of lists, in this case, iterate over a list of tuples.
tuple_list = [(1,2,3), (4,5,6), (7,8,9)] for triple in tuple_list: print(triple)
looping through multiple lists simultaneously is an essential part of the structure. Writing nested loops or multiple statements to traverse through various lists can be hectic. Simpler functionality of methods such as zip allows the programs to be much easier to cope with.