a=b=[1,2,3]
print (a is b) #True
But
a=[1,2,3]
print (a is [1,2,3]) #False
Why does the second part print False
?
a=b=[1,2,3]
print (a is b) #True
But
a=[1,2,3]
print (a is [1,2,3]) #False
Why does the second part print False
?
Multiple assignment in Python creates two names that point to the same object. For example,
>>> a=b=[1,2,3]
>>> a[0] = 10
>>> b
[10, 2, 3]
is
can be used to check whether two names (a
and b
) hold the reference to the same memory location (object). Therefore,
a=b=[1,2,3] # a and b hold the same reference
print (a is b) # True
Now in this example,
a = [1,2,3]
print (a is [1,2,3]) # False
a
does not hold the same reference to the object [1, 2, 3]
, even though a
and [1, 2, 3]
are lists with identical elements.
In case you want to compare whether two lists contain the same elements, you can use ==
:
>>> a=b=[1, 2, 3]
>>> a == b
True
>>>
>>> a = [1, 2, 3]
>>> a == [1, 2, 3]
True
Your first one explicitly makes a
and b
references to the object created by the list display [1,2,3]
.
In your second code, both uses of the list display [1,2,3]
necessarily create new list
objects, because lists are mutable and you don't want to implicitly share references to them.
Consider a simpler example:
a = []
b = []
a.append(1)
Do you want b
to be modified as well?
For immutable values, like int
s, the language implementation may cause literals to reuse references to existing objects, but it's not something that can be relied on.
the problem is the logic operator you are using.
You are asking are these identical object with is
and not if they are the equal (same data).
One is a reference to a object and the other is the object so even though they are equal the are not the same.
When you are setting a
and b
as the same list you are saying that a
and b
should be linked and should reference the same data so they are identical to each other but a
and b
are not the object [1,2,3]
they are a reference to a list that is the same.
==
- equal to (same).
is
- identical to.
So if you want to check if they are equal(same) use:
>>> a=[1,2,3]
>>> print (a == [1,2,3])
True
Similar question worth reading: Is there a difference between "==" and "is"?
Hope this helps, Harry.