how to use zip efficiently to iterate parallelly in multiple lists

Question:

Is there any way that while using the ZIP function we can provide some default value to parallel elements which are not present and still print the entire stuff?

eg, for the below code 6 from list a getting missed but I don’t want that to happen

a = [1,2,4,6]
b = [[1,3],[4,7],[6,1]]
for a,(b,c) in zip(a,b):
  print(a,b,c)

Asked By: code_dominar

||

Answers:

You can use zip_longest to provide default values for missing elements in your code:

from itertools import zip_longest

a = [1, 2, 4, 6]
b = [[1, 3], [4, 7], [6, 1]]

for a, (b, c) in zip_longest(a, b, fillvalue=(0, 0)):
    print(a, b, c)

This will print the following output:

1 1 3
2 4 7
4 6 1
6 0 0

In the example, zip_longest function adds a value of 0 for the missing elements in the input iterables. By default the zip_longest function will add a None value. You can change the filled value by specifying it in the fillvalue argument.

Answered By: Khalid

The zip_longest function from itertools should achieve exactly what you want:

from itertools import zip_longest

a = [1,2,4,6]
b = [[1,3],[4,7],[6,1]]
for a,(b,c) in zip_longest(a,b, fillvalue=("NaN1", "NaN2")):
   print(a,b,c)
Answered By: JonnyOhneha
from itertools import zip_longest

x = [1,2,4,6]
y = [[1,3],[4,7],[6,1]]
for x,(y,z) in zip_longest(x,y, fillvalue=("NaN1", "NaN2")):

   print(x,y,z)
Answered By: Deepak Jadhav