Questions about tuple?
Alex Martelli
aleax at aleax.it
Sat Nov 9 02:42:18 EST 2002
Mindy wrote:
> Hey, given a tuple t(a,b), is there any function in
> Python that I can get a, b individually from t?
> Actually, I have a list whose element is tuples. Say:
>
> tuple_list = [(1,'a'),(3,'b'),(2,'l'),(8,'p')]
>
> Then I want to get two lists from this tuple_list. The
> first list contains the first elements in the tuple of
> the tuple_list.
>
> first_list = [1,3,2,8]
>
> And the second list contains all the second elements,
> also maintaining the original order as in tuple_list.
>
> second_list = ['a','b','l','p']
>
> So how to get this easily? Thanks!
Probably easiest is with list comprehensions:
first_list = [ first for first, second in tuple_list ]
second_list = [ second for first, second in tuple_list ]
One alternative (more verbose, maybe even simpler)
is with an explicit loop:
first_list = []
second_list = []
for first, second in tuple_list:
first_list.append(first)
second_list.append(second)
Yet another (more concise, maybe a bit obscure) hinges
on built-in function zip and the *args construct for
passing all items of a sequence as individual positional
parameters:
first_list, second_list = map(list, zip(*tuple_list))
zip(*tuple_list) would by nature return a list of
TUPLES, i.e. (1, 3, 2, 8) and ('a', 'b', 'l', 'p'),
rather than of lists as you wish -- which is why we
map the built-in callable named `list` (costructor
of the list type) over the result to build a list
from each of the tuples. A similar idea can also
use list comprehensions rather than map, of course:
first_list, second_list = [list(x) for x in zip(*tuple_list)]
As you can see, we're alas quite a way from our ideal
of "one, and preferably only one, obvious way" to perform
a task. Personally, I'd choose the very first idiom I
suggested here, to repeat:
first_list = [ first for first, second in tuple_list ]
second_list = [ second for first, second in tuple_list ]
on the grounds that it IS obvious -- indeed, utterly
simple. "Do the simplest thing that can possibly work"...
Alex
More information about the Python-list
mailing list