[Tutor] why can you swap an immutable tuple?
Mark Lawrence
breamoreboy at yahoo.co.uk
Sat May 25 21:23:39 CEST 2013
On 25/05/2013 19:56, Jim Mooney wrote:
> I thought tuples were immutable but it seems you can swap them, so I'm
> confused:
>
> a,b = 5,8
You've defined two names a and b so where's the tuple?
>
> print a # result 5
>
> a,b = b,a
You've redefined two names a and b to take the values that were held in
b and a so still no tuple.
>
> print a # result 8, so they swapped
>
> # but if I test the type of a,b I get a tuple
>
> testit = a,b
Finally a tuple.
> print type(testit) #comes out as a tuple
>
> 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
Exactly as expected. So what precisely don't you understand?
>
> --
> Jim Mooney
>
> "Coding? You can get a woman to do that!" he said with a sneer. --heard
> from a physics professor in 1969
>
--
If you're using GoogleCrap™ please read this
http://wiki.python.org/moin/GoogleGroupsPython.
Mark Lawrence
More information about the Tutor
mailing list