Zip with list output instead of tuple Zip with list output instead of tuple python python

Zip with list output instead of tuple


If you are zipping more than 2 lists (or even only 2, for that matter), a readable way would be:

[list(a) for a in zip([1,2,3], [4,5,6], [7,8,9])]

This uses list comprehensions and converts each element in the list (tuples) into lists.


You almost had the answer yourself. Don't use map instead of zip. Use map AND zip.

You can use map along with zip for an elegant, functional approach:

list(map(list, zip(a, b)))

zip returns a list of tuples. map(list, [...]) calls list on each tuple in the list. list(map([...]) turns the map object into a readable list.


I love the elegance of the zip function, but using the itemgetter() function in the operator module appears to be much faster. I wrote a simple script to test this:

import timefrom operator import itemgetterlist1 = list()list2 = list()origlist = list()for i in range (1,5000000):        t = (i, 2*i)        origlist.append(t)print "Using zip"starttime = time.time()list1, list2 = map(list, zip(*origlist))elapsed = time.time()-starttimeprint elapsedprint "Using itemgetter"starttime = time.time()list1 = map(itemgetter(0),origlist)list2 = map(itemgetter(1),origlist)elapsed = time.time()-starttimeprint elapsed

I expected zip to be faster, but the itemgetter method wins by a long shot:

Using zip6.1550450325Using itemgetter0.768098831177