Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
985 views
in Technique[技术] by (71.8m points)

list - Why does "[] is [ ]" evaluate to False in python

Try this in an interactive python shell.

[] is [ ]

The above returns False, why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You created two mutable objects, then used is to see if those are the same object. That should definitely return False, or something would be broken.

You wouldn't ever want is to return true here. Imagine if you did this:

foo = []
bar = []
foo.append(42)

then you'd be very surprised if bar now contains 42. If is returned true, meaning that both [] invocations returned the exact same object, then appending to foo would be visible in the reference to bar.

For immutable objects, it makes sense to cache objects, at which point is may return true, like with empty tuples:

>>> () is ()  # are these two things the same object?
True

The CPython implementation has optimised empty tuple creation; you'll always get the exact same object, because that saves memory and makes certain operations faster. Because tuples are immutable, this is entirely safe.

If you expected to test for value equality instead, then you got the wrong operator. Use the == operator instead:

>>> [] == []  # do these two objects have the same value?
True

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...