Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty list is equal to None or not? [duplicate]

Possible Duplicate:
Why does “[] == False” evaluate to False when “if not []” succeeds?

I am new to python as per ternary operator of python

>>> 'true' if True else 'false'  true
   true

i am expecting for below code output as [] because [] not equal to None

>>> a=[]
>>> a==None
False
>>> a if a else None
None

pleas correct if i am wrong

Thanks hema

like image 741
user1559873 Avatar asked Dec 10 '12 17:12

user1559873


People also ask

Is Empty list same as none?

Usually, an empty list has a different meaning than None ; None means no value while an empty list means zero values.

Is Empty list True or false?

Empty lists are considered False in Python, hence the bool() function would return False if the list was passed as an argument.

What is empty list?

The emptyList() method of Java Collections class is used to get a List that has no elements. These empty list are immutable in nature.

Does empty list evaluate to none Python?

In Python, empty lists evaluate False , and non-empty lists evaluate True in boolean contexts. Therefore, you can simply treat the list as a predicate returning a Boolean value. This solution is highly Pythonic and recommended by the PEP8 style guide.


2 Answers

The empty list, [], is not equal to None.

However, it can evaluate to False--that is to say, its "truthiness" value is False. (See the sources in the comments left on the OP.)

Because of this,

>>> [] == False
False
>>> if []:
...     print "true!"
... else:
...     print "false!"
false!
like image 56
jdotjdot Avatar answered Oct 21 '22 15:10

jdotjdot


None is the sole instance of the NoneType and is usually used to signify absence of value. What happens in your example is that the empty list, taken in boolean context, evaluates to False, the condition fails, so the else branch gets executed. The interpreter does something along the lines of:

>>> a if a else None
    [] if [] else None
    [] if False else None
None

Here is another useful discussion regarding None: not None test in Python

like image 26
ank Avatar answered Oct 21 '22 15:10

ank