+2 votes
in Programming Languages by (73.8k points)
edited by

zip() function works fine on two lists of the same size, however, it drops the elements from the bigger list if lists are of different size. How can I keep all the elements using zip()?

E.g. if a=[1,3,5,7] and b=[2,4,6,8,10], the output should be [(1, 2), (3, 4), (5, 6), (7, 8), (,10)]

and 

if a=[1,3,5,7,9] and b=[2,4,6,8], the output should be [(1, 2), (3, 4), (5, 6), (7, 8), (9,)]

1 Answer

+1 vote
by (348k points)
selected by
 
Best answer

I think only zip() function will not solve your problem. You need to do some additional thing to get your desired output. Try the following code:

>>> a=[1,3,5,7]
>>> b=[2,4,6,8,10]
>>> zip(a, b) + [tuple([x]) for x in a[len(b):]] + [tuple([x]) for x in b[len(a):]]
[(1, 2), (3, 4), (5, 6), (7, 8), (10,)]

Also, I am not sure if you can get (,10) in the output. I tried different approaches, but it seems that tuple does not allow first element empty.


...