[Tutor] why can you swap an immutable tuple?

David bouncingcats at gmail.com
Sun May 26 03:34:38 CEST 2013


On 26/05/2013, Jim Mooney <cybervigilante at gmail.com> wrote:
> I thought tuples were immutable but it seems you can swap them, so I'm
> confused:
>
> a,b = 5,8

I think your confusion might arise from not understanding that the
meaning of the comma differs depending on whether it is on the left or
the right side of an equals sign.

On the right: it combines the 5 and the 8 to create a tuple, as yet un-named.

On the left: it says to unpack the tuple-on-the-right into two
independent values and assign them to the names a and b. So here it is
effectively a=5 and b=8.

So, there is no tuple on the left hand side. The statement does not
create a tuple, because the comma on the left side means "unpack the
tuple-on-the-right".

To assign a name to a tuple, there must be no comma on the left side, like this:
name_of_tuple = 5, 8


More information about the Tutor mailing list