Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two variables with 'is' operator which are declared in one line in Python [duplicate]

According to the Documentation:

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. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-)

So the following behaviors are normal.

>>> a = 256
>>> b = 256
>>> a is b
True
>>> c = 257
>>> d = 257
>>> c is d
False

But when i declare two variables like these, i am getting True-

>>> e = 258; f=258;
>>> e is f
True

I have checked the identity of the objects referenced by e and f-

>>> id(e)
43054020
>>> id(f)
43054020

They are same.

My question is what is happening when we are declaring e and f by separating with semicolons? Why are they referencing to the same object (though the values are out of the range of Python's array of integer objects) ?

It would be better, if you please explain it like you are explaining it to a beginner.

like image 544
ni8mr Avatar asked Aug 28 '15 04:08

ni8mr


People also ask

What is the correct way of comparing two variables in Python?

The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and != , except when you're comparing to None .

Which operator is used to compare two values Python?

The operator “==” compares values of two objects, while “is” checks if two objects are same (In other words two references to same object).

Is vs == for string comparison Python?

Python has the two comparison operators == and is . At first sight they seem to be the same, but actually they are not. == compares two variables based on their actual value. In contrast, the is operator compares two variables based on the object id and returns True if the two variables refer to the same object.


1 Answers

This is not an unexpected behavior, according to Python Data model it's an implementation detail:

Types affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. E.g., after a = 1; b = 1, a and b may or may not refer to the same object with the value one, depending on the implementation, but after c = []; d = [], c and d are guaranteed to refer to two different, unique, newly created empty lists. (Note that c = d = [] assigns the same object to both c and d.)

like image 118
Nir Alfasi Avatar answered Oct 09 '22 01:10

Nir Alfasi