Python | Loop over multiple lists at the same time

Python Methods and Functions

Loop through several lists at the same time

For a better understanding of iterating over multiple lists, we iterate over more than 3 lists at the same time.

We can iterate over lists simultaneously in the following ways:

  1. zip () and izip () : In Python, zip returns a list of tuples. It's good when the lists are not massive. If they are massive, then forming zip (list1, list2,….) Is an unnecessarily massive temporary variable and should be replaced with itertools.izip or itertools.izip_longest , which returns an iterator instead of a list. The zip () function stops when someone from the list of all lists is exhausted. Simply put, it works down to the smallest of all lists.

    Below is an implementation of the zip function and itertools.izip that iterates over 3 lists:

    # Python program for iteration
    # more than 3 lists using zip and izip functions

     

    import itertools 

     

    num = [ 1 , 2 , 3 ]

    color = [ 'red' , ' while' , 'black' ]

    value = [ 255 , 256 ]

     
    # iterates over 3 lists and justifies
    # 2 times as len (value) = 2, which is
    # minimum of all three

    for (a, b, c) in zip (num, color, value):

    print a, b, c

     

    print " iterating using izip "

    for (a, b, c) in itertools.izip (num, color, value):

    print a, b, c

    Exit:

     1 red 255 2 while 256 iterating using izip 1 red 255 2 while 256 
  2. itertools.izip_longest () : izip_longest stops when all lists are exhausted. When the shorter iterators are exhausted, izip_longest returns a tuple with the value None.

    The following is an implementation of the itertools.izip_longest file that repeats three lists:

    # Python program for iteration
    # more than 3 lists using zip and izip functions

     

    import itertools 

     

    num = [ 1 , 2 , 3 ]

    color = [ ' red' , 'while' , 'black' ]

    value = [ 255 , 256 ]

     
    # iterates over 3 lists and until all are exhausted

    for (a, b, c) in itertools.izip_longest (num, color, value):

    print a, b, c

    Exit:

     1 red 255 2 while 256 3 black None 




Get Solution for free from DataCamp guru