Pythonic way for checking equality in AND condition

Viewed 52

I have a piece of code which looks like below:

a = None
b = None
c = None
d = None

if a==None and b==None and c==None and d==None:
    print("All are None")
else:
    print("Someone is not None")

What would be the pythonic way or shorter way to achieve this as I have more number of variables to check like this?

3 Answers

You can use a list, and check all items in the list using list comprehension:

l_list = [None, None, None, None, None]
if all(item is None for item in l_list):
    print("All items are None")

You can chain the comparisons:

if a is b is c is d is None:
    print("All are None")
else:
    print("Someone is not None")

if not all((a, b, c, d)):

or

if not any((a, b, c, d)): if you want to check if any of the item is not None

Does this help?

Related