Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do boolean operations on lists mean?

Tags:

python

boolean

I was going through the source of pyftpdlib and I found this:

if self.rejected_users and self.allowed_users: raise AuthorizerError("rejected_users and allowed_users options are mutually exclusive")

rejected_users and allowed_users are lists. What's confusing me is how the and operator operates on two lists. I'd appreciate it if someone helped me out.

like image 315
sayantankhan Avatar asked Dec 12 '22 11:12

sayantankhan


2 Answers

All objects in Python have a boolean 'value'; they are either true or false in a boolean context.

Empty lists are false. This applies to all sequences and containers, including tuples, sets, dictionaries and strings.

Numeric 0 is false too, so 0, 0.0, 0j are all false as well, as are None and of course False itself:

>>> bool([])
False
>>> bool([1, 2])
True
>>> bool(0)
False
>>> bool('')
False

Everything else is considered true in a boolean context; so a list that is not empty is true, and two non-empty lists together with and is considered true as well.

You can make custom types look like empty containers by implementing __len__() and returning 0, or look like a number by implementing __nonzero__()* and returning False when the instance is to be the boolean equivalent of numeric zero.

Just remember that and and or shortcircuit; if the first expression locks in the result then that value is returned and the second expression is ignored altogether. For and, that means that in the expression x and y, y is ignored if x is a false value (like an empty list), because the whole expression can never be true in that case. For x or y, y is ignored if x is a true value.

These rules are all covered by the Boolean operations reference documentation.

*In Python 3, use __bool__ instead.

like image 150
Martijn Pieters Avatar answered Dec 31 '22 12:12

Martijn Pieters


Empty list evaluates to False and non-empty list evaluates to True.

if list1 and list2:

is equivalent to:

if list1 is not empty and list2 is not empty:


List of falsy values in python:

  • None

  • False

  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.

  • any empty sequence, for example, '', (), [].

  • any empty mapping, for example, {}.

  • instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False.

All other values are considered true — so objects of many types are always true.

like image 21
Ashwini Chaudhary Avatar answered Dec 31 '22 13:12

Ashwini Chaudhary