šŸ Advanced Python List Comprehensions with Conditional Expressions

a place of mind
5 min readOct 25, 2022

List comprehensions are actually nothing but a list() function applied to a generator object. Letā€™s create a list and a function that takes x and returns x^2:

Photo by a place of mind

A list comprehension is just syntax sugar for the last two lines, so we can simplify things like so:

If ā€¦ Else Conditions?

Notice that the if condition() inside the list comprehension merely filters x. We could just as well write:

Photo by a place of mind

Here, we manually filter our l list using a lambda function that returns a boolean: If x % 2 == 0 it returns True andFalse otherwise. The output of filter is a filter object. Here I converted it to a list and then applied our simple function f on it using map. But the list conversion is not necessary in this case, we could just say:

Again, we see that list comprehensions are syntax sugar for this complex code. However, with list comprehensions, you are limited to only if statements, no else. What if you wanted to apply f to even values of l and -f to odd values? The following snippet shows us that list comprehensions are not capable of doing this:

--

--