Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does tuple unpacking differ from normal assignment? [duplicate]

From this link I learnt that

The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object

But when I tried to give some example for my session and I found out that it behaves differently with assignment and tuple unpacking.

Here is the snippet:

>>> a,b = 300,300
>>> a is b
True
>>> c = 300
>>> d = 300
>>> c is d
False
like image 667
James Avatar asked Dec 22 '13 12:12

James


1 Answers

Because int is immutable, Python may or may not use exists object, if you save the following code in to a script file, and run it, it will output two True.

a, b = 300, 300
print a is b

c = 300
d = 300
print c is d

When Python compile the code, it may reuse all the constants. Becasue you input your code in a python session, the codes are compiled line by line, Python can't reuse all the constants as one object.

The document only says that there will be only one instance for -5 to 256, but doesn't define the behavior of others. For immutable types, is and is not is not important, because you can't modify them.

like image 52
HYRY Avatar answered Oct 17 '22 01:10

HYRY