In this short article I describe how to use conditional expressions in list comprehensions.
Conditional expressions in list comprehensions can be quite powerful because they let us write more flexible comprehensions.
List comprehensions start with an expression that modifies values. Typically, you always modify values in the same way, with the same function or formula. However, sometimes you may want to adapt the modification to the value itself.
Here's an example using the Collatz sequence:
# Google for the Collatz conjecture; # Take a number n, and do a step: # odd numbers go n -> 3 * n + 1 # even numbers go n -> n // 2 # Compute 1 step for some initial numbers: steps =  for n in range(100): if n % 2: steps.append(3 * n + 1) else: steps.append(n // 2)
Notice how, in the example above, we always want to append to the final list.
It's just that we want to append one of two different things, depending on
n % 2.
This is where a conditional expression comes in:
steps =  for n in range(100): # Compute next value depending on n % 2 step = 3 * n + 1 if n % 2 else n // 2 steps.append(step)
At this point, the classic list comprehension pattern arises and you can rewrite the loop above as a list comprehension. To give you a hand, I did it for you below. When using a conditional expression, I like to have the conditional expression by itself:
steps = [ 3 * n + 1 if n % 2 else n // 2 # How to modify n for n in range(100) # Where to get n from ]
To conclude, beware of a source of confusion:
forto filter values.
They do different things, and
... if ... else ...; while
I hope you learned something new! If you did, consider following the footsteps of the readers who bought me a slice of pizza 🍕. Your small contribution helps me produce this content for free and without spamming you with annoying ads.