Search code examples
pythonlistzippython-itertools

Iterating through list of list without knowing number of inner lists


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?


Solution

  • 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.