[Tutor] Getting single values of a tuple & storing them

Alan Gauld alan.gauld at btinternet.com
Thu Nov 1 09:22:56 CET 2007


"Trey Keown" <trey at opmstech.org> wrote

> I was wondering, how could I get each value inside of a tuple, say 
> it's
> (2,4) .
> The only value I really need is the second one (the tuple will 
> always have
> only two values.

Tuples are like any other Python collection or sequence.
You can access by indexing into the tuple:

second = tup[1]   # zero based index

you can also iterate over them:

for index, item in enumerate(tup):
   print index, item
   if index = 1: second = item

And additionally collections can be 'unpacked':

one, two, three = (1,2,3)

These techniques also work with lists and strings.

So pick the method that suits you best.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list