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. You can remove duplicates from a list in Python with For Loop.
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.