The specific problem has already been addressed in previous answers, so I will focus on the general concept of using conditionals inside list comprehensions.
Here are some examples that demonstrate how to write conditionals within a list comprehension:
X = [1.5, 2.3, 4.4, 5.4, 'n', 1.5, 5.1, 'a'] # Original list
# Extract non-strings from X into a new list
X_non_str = [el for el in X if not isinstance(el, str)] # When using only 'if', place 'for' at the beginning
# Replace all strings in X with 'b', while preserving everything else
X_str_changed = ['b' if isinstance(el, str) else el for el in X] # When using 'if' and 'else', place 'for' at the end
In the first list comprehension for X_non_str
, the order is:
expression for item in iterable if condition
In the second list comprehension for X_str_changed
, the order is:
expression1 if condition else expression2 for item in iterable
It can be tricky to remember that expression1
must come before if
and expression2
must come after else
. This structure resembles natural language, for example, “I want to stay inside if it rains, else I want to go outside.”
In plain English, the two types of list comprehensions mentioned above could be described as:
With only if
:
extract_apple for apple in apple_box if apple_is_ripe
And with if/else
:
mark_apple if apple_is_ripe else leave_it_unmarked for apple in apple_box