Efficiently Split A List of Tuples
Paul Rubin
http
Wed Jul 13 20:20:28 EDT 2005
Richard <none at pacbell.net> writes:
> I have a large list of two element tuples. I want two separate
> lists: One list with the first element of every tuple, and the
> second list with the second element of every tuple.
>
> I know I can use a 'for' loop and create two new lists
> using 'newList1.append(x)', etc. Is there an efficient way
> to create these two new lists without using a slow for loop?
Not really. You could get a little cutesey with list comprehensions
to keep the code concise, but the underlying process would be about
the same:
a = ((1,2), (3, 4), (5, 6), (7, 8), (9, 10))
x,y = [[z[i] for z in a] for i in (0,1)]
# x is now (1,3,5,7,9) and y is (2,4,6,8,10)
More information about the Python-list
mailing list