1

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?

1
  • well these variables comes from frontend, Commented Mar 9, 2022 at 6:54

3 Answers 3

5

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")
Sign up to request clarification or add additional context in comments.

1 Comment

This approach is working for me, but there are some more answers which is giving the same results as I want. If possible could you explain me which could be an efficient way?
2

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")

Comments

-1

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?

3 Comments

Nope, If I change None to some value in any of variable, it still goes in if condtion, it should go in else printing "Some one is not none". If all the variables are not None, then it goes to else condition
Since the OP is asking if items are None you need to test against it specifically. Consider the possibility that these variables might be 0, False, [], etc.
@Mark: Yes, I agree.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.