[Tutor] why can you swap an immutable tuple?
Steven D'Aprano
steve at pearwood.info
Sun May 26 04:38:19 CEST 2013
On 26/05/13 05:23, Mark Lawrence wrote:
> 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?
On the right hand side, 5,8 creates a tuple, which is then immediately unpacked to two individual values. You can see this by disassembling the code. In 2.7, you get this:
py> from dis import dis
py> code = compile("a, b = 5, 8", "", "exec")
py> dis(code)
1 0 LOAD_CONST 3 ((5, 8))
3 UNPACK_SEQUENCE 2
6 STORE_NAME 0 (a)
9 STORE_NAME 1 (b)
12 LOAD_CONST 2 (None)
15 RETURN_VALUE
Other versions may be slightly different, for example in Python 1.5 (ancient history!) the constant tuple (5, 8) is not created at compile-time, but at run-time:
# output of dis from Python 1.5:
0 SET_LINENO 0
3 SET_LINENO 1
6 LOAD_CONST 0 (5)
9 LOAD_CONST 1 (8)
12 BUILD_TUPLE 2
15 UNPACK_TUPLE 2
18 STORE_NAME 0 (a)
21 STORE_NAME 1 (b)
24 LOAD_CONST 2 (None)
27 RETURN_VALUE
But whenever it is created, the right hand side creates a tuple.
An interesting fact: on the left hand side, Python is very flexible with its sequence unpacking syntax. All of these are equivalent, where RHS (Right Hand Side) evaluates to exactly two items:
a, b = RHS
(a, b) = RHS
[a, b] = RHS
Note also that it is *sequence* unpacking, not *tuple* unpacking. Any sequence will work. Actually, any iterable object will work, not just sequences. But the name comes from way back in early Python days when it only worked on sequences.
--
Steven
More information about the Tutor
mailing list