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:

  • conditional expressions in the beginning; vs
  • using if after a for to filter values.

They do different things, and

  • the former always looks like ... if ... else ...; while
  • the latter cannot have an else.

This article was generated automatically from this thread I published on Twitter @mathsppblog. Then it was edited lightly.

Become a better Python ๐Ÿ developer ๐Ÿš€

+35 chapters. +400 pages. Hundreds of examples. Over 30,000 readers!

My book โ€œPydon'tsโ€ teaches you how to write elegant, expressive, and Pythonic code, to help you become a better developer. >>> Download it here ๐Ÿ๐Ÿš€.

Previous Post Next Post

Blog Comments powered by Disqus.