On 05/25/2013 02:56 PM, Jim Mooney wrote:
I thought tuples were immutable but it seems you can swap them, so I'm
confused:


The anonymous tuple object is immutable, but you just build one temporarily, extract both items from it, and destroy it.

a,b = 5,8


The a,b on the left hand side is a tuple-unpacking-syntax, where it takes whatever tuple (or list, or whatever else supports the protocol), and extracts the elements in order. a,b are not tied together in any sense.

print a  # result 5

a,b = b,a


Here you build another anonymous tuple that happens to be in the reverse order as the earlier one. Then you unpack it into two arbitrary variables, that only happen to be the same ones as you used before, and only happens to be the same ones as used on the right side.

print a  # result 8, so they swapped

# but if I test the type of a,b I get a tuple

testit = a,b
print type(testit)  #comes out as a tuple

Now you're building yet another tuple, and actually binding a name to it. So it won't go away at the end of the statement.


print testit, # result is (8,5)

# So how am I swapping elements of a tuple when a tuple is immutable?

#t rying so change a tuple since I just did it

testit[1] = 14  #program crashes - *TypeError: 'tuple' object does not
support item assignment *so the tuple I just changed is indeed immutable


This time you ARE trying to change a tuple, for the first time.


--
DaveA
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to