How can I do the following in Python?
row = [unicode(x.strip()) for x in row if x is not None else '']
Essentially:
- replace all the Nones with empty strings, and then
- carry out a function.
How can I do the following in Python?
row = [unicode(x.strip()) for x in row if x is not None else '']
Essentially:
The specific problem has already been solved in previous answers, so I will address the general idea of using conditionals inside list comprehensions.
Here is an example that shows how conditionals can be written inside a list comprehension:
Note that in the first list comprehension for
X_non_str
, the order is:and in the last list comprehension for
X_str_changed
, the order is:I always find it hard to remember that value1 has to be before if and value2 has to be after else. My head wants both to be either before or after.
I guess it is designed like that because it resembles normal language, e.g. "I want to stay inside if it rains, else I want to go outside"
Here is another illustrative example:
It exploits the fact that
if i
evaluates toFalse
for0
and toTrue
for all other values generated by the functionrange()
. Therefore the list comprehension evaluates as follows:One way:
Although then you have:
Or you can use a lambda inline.
You can totally do that, it's just an ordering issue:
Note that this actually uses a different language construct, a conditional expression, which itself is not part of the comprehension syntax, while the
if
after thefor…in
is part of list comprehensions and used to filter elements from the source iterable.Conditional expressions can be used in all kinds of situations where you want to choose between two expression values based on some condition. This does the same as the ternary operator
?:
that exists in other languages. For example:The other solutions are great for a single
if
/else
construct. However, ternary statements within list comprehensions are arguably difficult to read.Using a function aids readability, but such a solution is difficult to extend or adapt in a workflow where the mapping is an input. A dictionary can alleviate these concerns: