-1
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 ?

Giorgos Myrianthous
  • 36,235
  • 20
  • 134
  • 156
Mentalist
  • 11
  • 1
  • This mighy helpful https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is – Barış Can Tayiz Feb 29 '20 at 22:29
  • Because in the first example a and b are the same list. In the second you have two lists with the same content. `is` is not the same as `==`. – khelwood Feb 29 '20 at 22:29

3 Answers3

2

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
Giorgos Myrianthous
  • 36,235
  • 20
  • 134
  • 156
1

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 ints, the language implementation may cause literals to reuse references to existing objects, but it's not something that can be relied on.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

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.

Why your results

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.

In summary

== - 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.

Harry S
  • 985
  • 5
  • 6