Skip to content
Advertisement

How to get all the Falsy variables without using `if` statements

Let’s say I have multiple variables like:

x = 0
y = 2

if x and y:
   pass

How can I determine which of the variables are not True? I am trying to identify this without using the if statements. For the above example, I want to just get 0 (falsy value) skipping the 2 (truthy value).

Advertisement

Answer

You can create a tuple of all your variables. And then use itertools.filterfalse() with bool as predicate value to get all the Falsy values from tuple as:

>>> from itertools import filterfalse
>>> my_list = (1, "a", False, 2.34, "", 0)

>>> list(filterfalse(bool, my_list))
[False, '', 0]

Similarly if you need a list of all the Truthy values, you can use filter() as:

>>> my_list = (1, "a", False, 2.34, "", 0)

>>> list(filter(bool, my_list))
[1, 'a', 2.34]
Advertisement