[Tutor] Splitting a Tuple in Python 2.7

Dave Angel d at davea.name
Tue Dec 6 04:07:35 CET 2011


On 12/05/2011 09:31 PM, Greg Nielsen wrote:
> The following gets returned from a function that I am calling.
>
> (120, 400)
>
> While I can use the Tuple as is in my program, I would like the ability to
> change one or even both of the numbers depending on other events that
> happen. So here is my question, is there a way to either 1) save each part
> of the Tuple into a seperate variable or 2) edit just one part of the Tuple
> without knowing or affecting the other number. Thanks for the help!
>
> Greg
>
To extract the individual elements, you can use [0] and [1]

However, you cannot change an element, since a tuple is immutable.  You 
have to build a new tuple.  Or you can use a list, which is not immutable.

a = (3, 5)
print a[0]       # you get 3

b = a[0], 42
print b         # you get (3, 42)

c,d = a      # c gets 3 and d gets 5


-- 

DaveA



More information about the Tutor mailing list