1

I have the following code:

a = []
b = a

when I compile the following code I get this:

print(b is a) --> True
print(b is []) --> False

if b = a then shouldn't b is [] return True?

5
  • 3
    is means referential equality, so that both things refer to the same object, two separate lists are not the same object. Commented Jul 31, 2019 at 21:46
  • 3
    No, not at all. Equality is not identity Commented Jul 31, 2019 at 21:46
  • 1
    Whether a literal produces a new object or refers to an existing object is basically an implementation detail. Don't use is with literals. Commented Jul 31, 2019 at 21:47
  • 2
    I should say, for immutable values it is an implementation detail. For mutable values, caching a value will cause problems. Commented Jul 31, 2019 at 21:48
  • Not all [] are the same object. [] is just an empty list, which can be constructed in many ways. Commented Jul 31, 2019 at 22:12

1 Answer 1

5

try that:

    a = []
b = a


print(id(a))
print(id(b))
print(id([]))

And you will see that a and b refers to the same object, while next [] is a different one. Check if b to see if b is not empty list

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.