Reputation: 9
a = [1,2,3]
b = [1,2,3]
I understand a is b
is false but i can't understand a is [1,2,3]
is false
I learned variable is like nickname for objects like x = 2
and id(x) == id(2)
but id(a)
is not as same as id(b)
...
In this case, a is an object? not a variable?
Upvotes: 0
Views: 525
Reputation: 1228
Variables are references to objects. a
does not reference the same object as b
. Even though the two objects are the same they have unique addresses in memory and do not depend on each other.
>>> a = b = [1,2,3]
>>> c = [1,2,3]
>>> print(a is b)
True
>>> print(a is c or b is c)
False
>>> a.remove(1)
>>> print(a)
[2, 3]
>>> print(b)
[2, 3]
>>> print(c)
[1, 2, 3]
In the case of the x = 2
and id(x) == id(2)
integers are immutable and in CPython id
is simply the location of an object in memory. Integers are always the same so storing the same integer several times at different addresses would be a waste of memory.
However, in general DO NOT use integers with is
operator as it can lead to different results across different python implementations.
Upvotes: 1
Reputation: 483
Everything in Python is an object. a is b
evaluates to false because, as you know, they are not the same object. They are both instances of the List
class, therefore having different locations in memory, and being completely separate in every way except their class structure, or blueprint, as you can think of it. id(a)
and id(b)
will reflect this, they are not the same object and will therefore not share an ID. This is a reference to their location in memory, and while IDs are not referenced pointers, they are similar in that they describe their not being the same.
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> id(a) == id(b)
False
>>> # the below is an example, every session will result in a different ID,
>>> # as it's being stored at a unique mem location each time
>>> id(a)
2770873780160
>>> id(b)
2770873412800
>>> id(a) - id(b) # simply to show the difference in location.
367360
https://www.tutorialspoint.com/difference-between-and-is-operator-in-python
Upvotes: 0