5

When I'm trying to check whether a list is empty or not using python's not operator it is behaving in a weird manner.

I tried using the not operator with a list to check whether it is empty or not.

>>> a = [] >>> not (a) True >>> not (a) == True True >>> not (a) == False True >>> True == False False 

The expected output for not (a) == False should be False.

2 Answers 2

11

== has higher precedence than not. not (a) == False is parsed as not (a == False).

Sign up to request clarification or add additional context in comments.

Comments

2

This is working as expected. Parenthesis added below to clarify how this is being executed:

not (a == True) # True not (a == False) # True 

An empty list, a = [], evaluates to False in boolean expressions, but it does not equal False or True. Your expressions in the middle are testing whether it is equal to False or True, so they both evaluate to False, and not False is True.

You can add parenthesis like below to get what you expect:

(not a) == True # True (not a) == False # False 

1 Comment

For completeness sake: you can cast to bool to force a Boolean evaluation. bool([]) returns False. So: bool(a) == False and even bool(a) is False are both True.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.