Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to use zip efficiently to iterate parallelly in multiple lists

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

The zip_longest function automatically adds a default value of 0 for the missing elements in the input iterables. You can change the default value to any other value that you want to use, by specifying it in the fillvalue argument.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading