Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python "is" statement: what is happening? [duplicate]

Tags:

python

I was quite surprised when

[] is not [] 

evaluated to True.

What is happening in this code? What really not and is statements are doing?

like image 665
fjsj Avatar asked Sep 15 '10 14:09

fjsj


People also ask

What is the IS statement in Python?

is means is same instance. It evaluates to true if the variables on either side of the operator point to the same object and false otherwise.

Can an if statement have multiple conditions Python?

Python supports multiple independent conditions in the same if block. Say you want to test for one condition first, but if that one isn't true, there's another one that you want to test. Then, if neither is true, you want the program to do something else. There's no good way to do that using just if and else .

How do you check multiple conditions in one if statement?

Here we'll study how can we check multiple conditions in a single if statement. This can be done by using 'and' or 'or' or BOTH in a single statement. and comparison = for this to work normally both conditions provided with should be true. If the first condition falls false, the compiler doesn't check the second one.

Why is Python's print a statement rather than a function or expression?

This is because they both have a function defined called print that takes in a string argument and prints it. Python2 also allowed you to make a statement to print to standard out without calling a function.


2 Answers

a is not b is a special operator which is equivalent to not a is b.

The operator a is b returns True if a and b are bound to the same object, otherwise False. When you create two empty lists you get two different objects, so is returns False (and therefore is not returns True).

like image 124
Mark Byers Avatar answered Sep 28 '22 15:09

Mark Byers


is is the identity comparison.

== is the equality comparison.

Your statement is making two different lists and checking if they are the same instance, which they are not. If you use == it will return true and because they are both empty lists.

like image 34
unholysampler Avatar answered Sep 28 '22 16:09

unholysampler