Skip to content Skip to sidebar Skip to footer

How To Avoid Multiple Flat If Conditions In Python?

Consider the snippet: def check_conditions(range_of_numbers): #method returns a list containing messages list1 = [] if condition1: list1.append('message1') if c

Solution 1:

just loop on the condition/message couples for instance:

forcondition,message in ((condition1,"message1"),(condition2,"message2"),(condition3,"message3")):
    if condition:
       list1.append(message)

if the conditions are exclusive, consider adding a break if one condition matches.

list comprehension version (more "pythonic" but not possible to break on first condition match, though):

list1 = [message for condition,message in ((condition1,"message1"),(condition2,"message2"),(condition3,"message3")) if condition]

Solution 2:

As a supplement of Jean-FrançoisFabre.

All conditions are satisfied

tmp = [message for condition, message in ((condition1, "message1"),
       (condition2, "message2"),(condition3, "message3")) if condition]

Conditions are exclusive

tmp = next((message forcondition, message in ((condition1, "message1"),         
           (condition2, "message2"), (condition3, "message3")) if condition), None)

Post a Comment for "How To Avoid Multiple Flat If Conditions In Python?"