š Advanced Python List Comprehensions with Conditional Expressions
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
:
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:
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: