Search code examples
pythonlisttuples

How to convert list of tuples to multiple lists?


Suppose I have a list of tuples and I want to convert to multiple lists.

For example, the list of tuples is

[(1,2),(3,4),(5,6),]

Is there any built-in function in Python that convert it to:

[1,3,5],[2,4,6]

This can be a simple program. But I am just curious about the existence of such built-in function in Python.


Solution

  • The built-in function zip() will almost do what you want:

    >>> list(zip(*[(1, 2), (3, 4), (5, 6)]))
    [(1, 3, 5), (2, 4, 6)]
    

    This will give you a list of tuples. If you want to go further and arrive at a list of lists:

    >>> list(map(list, zip(*[(1, 2), (3, 4), (5, 6)])))
    [[1, 3, 5], [2, 4, 6]]