Search code examples
pythonlistpython-3.xtransposenonetype

Python - Transpose List of Lists of various lengths - 3.3 easiest method


a=[[1,2,3],[4,6],[7,8,9]]

In Python 2 If I have a list containing lists of variable lengths then I can do the following:

list(map(None,*a))

Result:

[(1, 4, 7), (2, 6, 8), (3, None, 9)]

In Python 3 None type is seemingly not accepted.

Is there, in Python 3, an as simple method for producing the same result.


Solution

  • You can use itertools.zip_longest in Python 3:

    >>> from itertools import zip_longest
    >>> list(zip_longest(*a))
    [(1, 4, 7), (2, 6, 8), (3, None, 9)]