WorkoutBuddy
WorkoutBuddy

Reputation: 759

Logical operatin in python: Value 1 or Value 2 not in list

Why does thins not work:

if "update" or "create" not in sys.argv:
    usage()
$ python myScript.py update
# In if

$ python myScript.py create
# In if

Goal: How can I check if neither "update" nor "create" is in the list, then the code in the if statement runs?

Upvotes: 1

Views: 171

Answers (2)

Arty
Arty

Reputation: 16775

Correct your code to:

if "update" not in sys.argv and "create" not in sys.argv:
    usage()

If you need to check many values from list of possible then use next solution with all():

if all((s not in sys.argv) for s in ["update", "create"]):
    usage()

Or another solution for list of values using sets-intersection, use next solution only when you need speed or lists are long, otherwise prefer previous solution with all() as more readable/understandable:

if len(set(["update", "create"]) & set(sys.argv)) == 0:
   usage()

Note: set(list_object) code constructs set from list each time this code is called, and takes time, hence if this code runs many times construct set in variable like a = set(list_a) and reuse a later many times.

Upvotes: 2

Axnyff
Axnyff

Reputation: 9984

Your code is equivalent to

if "update" or ("create" not in sys.argv):
    usage()

as "update" is truthy, it will always evaluate usage

What you meant is probably

if "update" not in sys.argv and "create" not in sys.argv:
    usage()

Upvotes: 1

Related Questions