Python Short-Cut: Complex if Conditions

If you have a complex if condition, such as:

x = 'third'
if x == 'first' or x == 'second' or x == 'third' or x == 'fourth':
    print(True)

You can use the following short-cut instead:

x = 'third'
if x in ['first', 'second', 'third', 'fourth']:
    print(True)

This creates much more readable code, especially the more conditions there are.

If you’re looking to see if a value exists as a key in a dictionary:

x = 'key2'
myDict = {'key1':'val1', 'key2':'val2', 'key3':'val3'}
keyList = list(myDict.keys())
if x in keyList:
    print(True)

Or looking to see if a value exists as a value in a dictionary:

x = 'val3'
myDict = {'key1':'val1', 'key2':'val2', 'key3':'val3'}
valList = list(myDict.values())
if x in valList:
    print(True)

If you’re looking to see if a value exists at the first item of any tuple in a list of tuples:

x = 'c'
tupleList = [('a','b'), ('c','d'), ('e','f')]
valList = [val[0] for val in tupleList]
if x in valList:
    print(True)

If you’re looking to see if a value exists as any item of a tuple in a list of tuples:

x = 'f'
tupleList = [('a','b'), ('c','d'), ('e','f')]
valList = [val[0] for val in tupleList] + [val[1] for val in tupleList]
if x in valList:
    print(True)

Leave a Comment

Your email address will not be published. Required fields are marked *