Monday, September 14, 2015

Unpacking argument lists in Python

What I want to achieve is to transpose the list of list or tupple:

original = [('First', 1, 3, 4), ('Second', 4, 5, 6)]

to

transposed = [('First', 'Second'), (1, 4), (3, 5), (4, 6)]

With itertools.izip I can solve my problem:

from itertools import izip
transposed = izip(original[0], original[1])

But, what if my original list contains 1000 lists/tuples? Fortunately, in Python, you can unpack the list as arguments. So, what I need to do is just:

transposed = izip(*original)


Pretty amazing huh?

References:
[0] https://docs.python.org/2/tutorial/controlflow.html#tut-unpacking-arguments
[1] http://stackoverflow.com/questions/4112265/how-to-zip-lists-in-a-list