WoJ
WoJ

Reputation: 30007

how to deal with numerous elements in a condition?

I sometimes need to use many elements in a condition, all being the same kind

args = list()
if "a" not in args or "b" not in args or "c" not in args:
    print("something is missing")

This gets complicated when the number of elements to test gets large. I tried to combine them in a list but the end result is ugly:

args = list()
for what in ["a", "b", "c"]:
    if what not in args:
        print("something is really missing")
        break

What would be a pythonic way to code this kind of situation (several components, all the same, to an if)?

Upvotes: 0

Views: 48

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 122067

The typical way to do this is with all:

if not all(arg in args for arg in ("a", "b", "c")):

Also, consider raising an error, rather than printing a message.

Upvotes: 1

Tony Suffolk 66
Tony Suffolk 66

Reputation: 9704

Using sets will work :

args = list(....)
if set(["a","b","c"]).issubset(args):
    print("something is really missing")

This works if the ordering does not matter - i.e. a,b,c can exist in any order in args, and if there can be other things in args (other than a,b,c)

Upvotes: 0

Related Questions