oneloop oneloop - 15 days ago 5
Python Question

Python: flattening a zip?

I have two list that I want to zip:

a = ((1,2,3), (4,5,6), ... )
h = ('a','b', ... )


A simple
zip(a,h)
returns this:

[ ((1,2,3),'a'), ((4,5,6),'b'), ... ]


Is there any clever way to return this?

[ (1,2,3,'a'), (4,5,6,'b'), ... ]

Answer

You can use tuple concatenation in a list comprehension:

>>> a = ((1, 2, 3), (4, 5, 6))
>>> h = ('a', 'b')
>>> [x + (y,) for x, y in zip(a, h)]
[(1, 2, 3, 'a'), (4, 5, 6, 'b')]
Comments