Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
982 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...