2

I have a list of list:

x = [[1,2,3], [4,2], [5,4,1]]

I want to traverse the elements in the inner list sequentially and get:

1 4 5
2 2 4
3 None 1

I've tried this but I couldn't get the last line:

>>> x = [[1,2,3], [4,2], [5,4,1]]
>>> a, b, c = x
>>> for i,j,k in zip(a,b,c):
...     print i,j,k
... 
1 4 5
2 2 4

Given that I don't know how many inner lists are there how do i do achieve the desired result?

alvas
  • 115,346
  • 109
  • 446
  • 738

2 Answers2

6

You can use itertools.izip_longest to pad the shorter sublists:

for t in izip_longest(*x):
    print t

Note the use of *x and t to deal with an unknown number of sublists.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
1
from itertools import izip_longest
x = [[1,2,3], [4,2], [5,4,1]]
for i in izip_longest(*x):
    print i

(1, 4, 5)
(2, 2, 4)
(3, None, 1)
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321