Search code examples
pythonlisttupleslist-comprehension

How to unzip a list of tuples into individual lists?


I have a list of tuples l = [(1,2), (3,4), (8,9)]. How can I, succinctly and Pythonically, unzip this list into two independent lists, to get [ [1, 3, 8], [2, 4, 9] ]?

In other words, how do I get the inverse of what zip does?


Solution

  • Use zip(*list):

    >>> l = [(1,2), (3,4), (8,9)]
    >>> list(zip(*l))
    [(1, 3, 8), (2, 4, 9)]
    

    The zip() function pairs up the elements from all inputs, starting with the first values, then the second, etc. By using *l you apply all tuples in l as separate arguments to the zip() function, so zip() pairs up 1 with 3 with 8 first, then 2 with 4 and 9. Those happen to correspond nicely with the columns, or the transposition of l.

    zip() produces tuples; if you must have mutable list objects, just map() the tuples to lists or use a list comprehension to produce a list of lists:

    map(list, zip(*l))          # keep it a generator
    [list(t) for t in zip(*l)]  # consume the zip generator into a list of lists