# Multiple if-statements with overwriting lists

I currently have the following piece of code in place that attempts to find matches within a list, based on a priority system:

possible_combinations = ["ABC", "AB", "A", "D"]

if len(possible_combinations) >= 1:
chosen_combination = [comb for comb in possible_combinations if ("A" in comb) and ("C" in comb)]
if (len(chosen_combination) == 0):
chosen_combination = [comb for comb in possible_combinations if ("A" in comb)]
if (len(chosen_combination) == 0):
chosen_combination = [comb for comb in possible_combinations if ("C" in comb)]
if (len(chosen_combination) == 0):
raise ValueError(f"No match found.")

print(chosen_combination)

['ABC']


Is there any way I could refactor this code to get rid of these if-statements, and thereby make my code look nicer?

• perhaps explain why/what, there might be completely different way to solve the problem Nov 4, 2020 at 17:48

You could do something like this:

possible_combinations = ["ABC", "AB", "A", "D"]
combs = [("A","C"),("A",),("C",)]

for comb in combs:
chosen_comb = [x for x in possible_combinations if all([y in x for y in comb])]
if len(chosen_comb) > 0:
break

print(chosen_comb)


• Are you sure that this: ("A","C"),("A"),("C") is your intent? The first parens make a tuple, and the second and third do not. Nov 4, 2020 at 18:33
• It doesn't really matter here, but you are right. What I meant was [("A","C"),("A",),("C",)]. I corrected it. Nov 4, 2020 at 19:37
• Looks quite nice. Thx! Nov 5, 2020 at 8:39