1

I understand that I can test if a list is empty like this:

l = []
if not l:
    print("empty")

But I do not understand why the next code isn't equivalent:

if l == False:
    print("empty")
Jean Zombie
  • 607
  • 1
  • 9
  • 28
  • 1
    It's very simple. `bool([]) = False ` but `[] != False` – qvpham Jul 15 '16 at 09:44
  • 1
    @julivicoit's not simple if you are new to Python. The key point is that `if not l` is actually implicitly invoking the bool() conversion on `l`. – Steve Jul 15 '16 at 09:53
  • @SteveHaigh: U are right. Now i can't edit my comment any more. So sorry for this! – qvpham Jul 15 '16 at 09:56

1 Answers1

0

l itself is list type so comparing it with boolean will always return False

not l is boolean expression so it will return True sometimes depending on if l is empty or not

    >>>l = []
    >>>type(l)
    <type 'list'>
    >>>l == True
    False
    >>>l == False
    False
    >>>
    >>>
    >>> type(not l)
    <type 'bool'>
    >>> (not l) == False
    False
    >>> (not l) == True
    True
m.antkowicz
  • 13,268
  • 18
  • 37