If you are just interested about the syntax of comprehension with if-else statement (😢) jump here.

If you ask me what is the feature that I like most about Python I would reply without esitation: comprehension!

Countless blog posts show how it works in detail, but for the sake of completeness let’s see a definition:

Comprehensions provide a short and concise way to construct new sequences (such as lists, set, dictionary etc.) using sequences which have been already defined.

Just to be clear “short and concise way” it’s a nice way to say without using an explicit for loop and append or similar.

Comprehension is better

Let’s make an example with my favorite food: pizza (It’s me Mario!🍕🇮🇹).

pizzas = ["margherita", "marinara", "pepperoni", "veggie"]

Since we consider pizzas really important, they deserve to be with capital letter. Instead of using a boring for cycle with append we can do this

pizzas = ["margherita", "marinara", "pepperoni", "veggie"]
pizzas = [item.capitalize() for item in pizzas] 

In a similar way if we have a dictionary with pizzas and ingredients we can determine the number of ingredients

pizzas_ingredients = {"Margherita": ["tomato", "mozzarella cheese"], "Marinara": ["tomato", "garlic"], "Pepperoni": ["tomato", "mozzarella cheese", "pepperoni"], "Veggie": ["tomato", "zucchini", "eggplant"]}
pizzas_number_ingredients = {pizza: len(ingredients) for pizza, ingredients in pizzas_ingredients.items()}

Of course we can create also a list from a dictionary, for istance to produce the shorthand names of the pizza (useful for the waiter) consisting in the first four letters of the name from the dictionary of pizza with ingredients

pizzas_ingredients = {"Margherita": ["tomato", "mozzarella cheese"], "Marinara": ["tomato", "garlic"], "Pepperoni": ["tomato", "mozzarella cheese", "pepperoni"], "Veggie": ["tomato", "zucchini", "eggplant"]}
pizzas_shorthand_names = [pizza[:4] for pizza in pizzas_ingredients.keys()]

We can also produce a dictionary from a list, for istance associating the pizza name with its length

pizzas = ["Margherita", "Marinara", "Pepperoni", "Veggie"]
pizzas_length = {item: len(item) for item in pizzas} 

Comprehension with if

The cool thing is that you can evaluate an if condition in the comprehension. For istance we can filter only pizzas that start with M

pizzas = ["Margherita", "Marinara", "Pepperoni", "Veggie"]
pizzas_start_m = [item for item in pizzas if item.startswith("M")] 

and we could use a similar syntax for dictionary comprehension. Supposing we have a dictionary that associates each pizza with its price we can filter those that cost more than 6 euros

pizza_prices = {"Margherita": 6, "Marinara": 5, "Pepperoni": 8, "Veggie": 7}
pizza_over_6 = {pizza: price for pizza, price in pizza_prices.items() if price > 6}

Comprehension with if-else

But here we come to the core point of this post: when using an if-else statement it’s easy to get stuck!

Syntax

List comprehension with an if-else can be written as

# pseudo-code
result = [expression_if_case if if_condition
          else expression_else_case for for_loop]

and dictionary comprehension as

# pseudo-code
result = {key: value_if_case if if_condition
          else value_else_case for for_loop}

Examples

We can write a string commenting wheater we like or not the type of pizza

pizzas = ["Margherita", "Marinara", "Pepperoni", "Veggie"]
liked_pizzas = ["Margherita", "Pepperoni"]
pizza_comments = [f"We like {item}" if item in liked_pizzas
                  else f"We don't want {item}" for item in pizzas]

Based on our preference we can take a pizza if we like it or zero if we don’t want it

pizzas = ["Margherita", "Marinara", "Pepperoni", "Veggie"]
liked_pizzas = ["Margherita", "Pepperoni"]
pizza_order = {item: 1 if item in liked_pizzas else 0 for item in pizzas}

And now it’s time for…pizza! See you next time you forget how to use if-else in comprehension.