Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

Try this in an interactive python shell.

[] is [ ]

The above returns False, why?

like image 966
Jonathan Avatar asked Mar 02 '17 10:03

Jonathan


People also ask

Is [] False in Python?

Logic Operations Every value in Python is either True or False, numbers are True if they are not zero, and other values are True if they are not empty. e.g. "" and [] are both False.

What evaluates to False in Python?

First, we look at what kind of values evaluate to "True" or "False" in python. Anything that is "empty" usually evaluates to False, along with the integer 0 and the boolean value of False. Objects that are not empty evaluate to "True", along with numbers not equal to 0, and the boolean value True.

How do you know if a Python is true or False?

You can check if a value is either truthy or falsy with the built-in bool() function. According to the Python Documentation, this function: Returns a Boolean value, i.e. one of True or False .

Is not none in Python?

Use the is not operator to check if a variable is not None in Python, e.g. if my_var is not None: . The is not operator returns True if the values on the left-hand and right-hand sides don't point to the same object (same location in memory).


2 Answers

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
like image 162
Martijn Pieters Avatar answered Oct 21 '22 03:10

Martijn Pieters


In python is does a reference equality check like [] and [] they are different objects you can check that by

print id([]),id([])

or

 In [1]: id([])
Out[1]: 140464629086976

In [2]: id([])
Out[2]: 140464628521656

both will return different address and both are different object so is will always give false

[] is []

output

false
like image 39
Anand Tripathi Avatar answered Oct 21 '22 03:10

Anand Tripathi