If/else in a list comprehension
Use a ternary operator for if/else
within a list comprehension:
For example, tagging numbers as "big"
or "small"
based on a threshold:
This gives you:
Where new_val
is allocated if the condition
holds true, else other_val
is used across each x
in the sequence
.
Building conditions in list comprehension
Let's define how to correctly construct conditions within the context of list comprehension to ensure we don't face the Python wrath AKA SyntaxError
.
Filtering with list comprehension
Filtering is typically done using a condition towards the end of the list comprehension as shown:
This removes any x
that does not meet the condition. For instance:
Will return only even numbers between 0 and 14, or as we call them, the "even gang":
Juggling multiple conditions
You can either nest or combine conditions depending on the complexity of your criteria:
-
Multiple conditions nested:
-
Multiple conditions combined:
Syntax: Order in the court!
The for
clause must always be the last thing in the comprehension when adding a condition. This helps keep things straight for Python.
Enhance element extraction and transformation
List comprehensions can make your element extraction or data transformation more efficient and concise.
In-list condition checks
You can make your list comprehension more readable by writing the condition before specifying what to iterate over:
Here's how you can replace None
values in a list with an empty string:
Use filter
to sanitize lists
filter
function can be leveraged to clean up the list before performing list comprehension:
Python's "truthiness" for the win
In Python, zero (0
) is considered False
while all other numbers are True
. Let's use that in our list comprehension:
And the result is:
Advanced usage and watch-outs
String join() for merging list items
If you ever wanted to merge list items into a single string with different outcomes based on conditions, join()
is your friend. Let's create a string of giggles, shall we?
And the laughter ensues:
When in doubt, separate!
When conditions get knotty, separate them into a function for cleaner list comprehension:
Lambda: the inline handler
Lambda function can be used in map
for inline handling:
Pitfalls to avoid
Complex conditions and deep nesting can be hard to unravel. Keep your comprehensions simple. If things are getting too complex, consider moving out the logic into separate functions or helper methods.
Was this article helpful?