Python - iterate over a list whose elements are of variable length

How can I iterate over a list or tuple whose elements are in the form of variable-length lists in Python? For example, I want to do

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

and then have elements tupthat are short to complete, say None. I found a workaround with the following code, but I believe there should be a better way.

tup=( [1,2], [2,3,5], [4,3], [4,5,6,7] )
for a,b,c,d in [ el if len(el)==4 else [ el[i] if i<len(el) else None for i in range(4)] for el in tup ]:
     print a,b,c,d

Where 4is actually the length of the longest element.

Is there a better way?

+4
source share
2 answers

To match your own output, you can use izip_longestto fill in with Noneand transpose again to return to the original order

from itertools import izip_longest

tup=( [1,2], [2,3,5], [4,3], [4,5,6,7] )
for a,b,c,d in zip(*izip_longest(*tup)):
    print(a,b,c,d)
(1, 2, None, None)
(2, 3, 5, None)
(4, 3, None, None)
(4, 5, 6, 7)

int, float .. , fillvalue izip_longest:

tup=( [1,2], [2,3,5], [4,3], [4,5,6,7])
for a,b,c,d in zip(*izip_longest(*tup,fillvalue=0)):
    print(a,b,c,d)

(1, 2, 0, 0)
(2, 3, 5, 0)
(4, 3, 0, 0)
(4, 5, 6, 7)

print, , , python2, , python3, @TimHenigan , , zip_longest.

, itertools.izip, :

 from itertools import izip_longest, izip

tup = ( [1, 2], [2, 3, 5], [4, 3], [4, 5, 6, 7])
for a, b, c, d in izip(*izip_longest(*tup, fillvalue=0)):
    print(a, b, c, d)
+7

Python 3 :

for i in tup:
    for j in i:
        print(j,"",end="")
    print()
0

All Articles