if not a:
print("List is empty")
Using the implicit booleanness of the empty list is quite Pythonic.
if not a:
print("List is empty")
Using the implicit booleanness of the empty list is quite Pythonic.
The Pythonic way to do it is from the PEP 8 style guide.
For sequences, (strings, lists, tuples), use the fact that empty sequences are false:
# Correct: if not seq: if seq: # Wrong: if len(seq): if not len(seq):
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,
Copy>>> [] == False
False
>>> if []:
... print "true!"
... else:
... print "false!"
false!
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:
Copy>>> 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