Questions about tuple?

Chad Netzer cnetzer at mail.arc.nasa.gov
Fri Nov 8 20:07:38 EST 2002


On Friday 08 November 2002 16:27, Mindy wrote:
> Hey, given a tuple t(a,b), is there any function in
> Python that I can get a, b individually from t?

if t is a tuple, then t[0] is the first element, t[1] is the second, etc.

you could also say:

   a,b = t

and a will equal the first element, and b the second (assuming t is a length 
2 tuple or list)

> Actually, I have a list whose element is tuples. Say:
>
> tuple_list = [(1,'a'),(3,'b'),(2,'l'),(8,'p')]

the old reliable way is:

first_list = []
second_list = []
for a,b in tuple_list:
    first_list.append( a )
    second_list.append( b )

Which you could make into a function if you need to do it often.

If you are using a recent python (say 2.1 or 2.2), you can possibly use list 
comprehensions, but I'll leave that for someone else to explain.

As a short note of style, calling it "tuple_list" is a bit misleading, 
because a tuple is not a list, and a list is not a tuple.  But they are both 
sequences, so I tend to use the label "seq" for such things if they are 
temporary, or the suffix "_seq" if I want to specify an object that is 
iterable.

You can always convert back and forth using the list() and tuple() 
constructors.

Hope this helps.

-- 

Chad Netzer
cnetzer at mail.arc.nasa.gov




More information about the Python-list mailing list