if/else in a list comprehension?


How can I do the following in Python?

row = [unicode(x.strip()) for x in row if x is not None else '']


  1. replace all the Nones with empty strings, and then
  2. carry out a function.
5/7/2019 9:57:30 PM

Accepted Answer

You can totally do that, it's just an ordering issue:

[unicode(x.strip()) if x is not None else '' for x in row]

In general,

[f(x) if condition else g(x) for x in sequence]

And, for list comprehensions with if conditions only,

[f(x) for x in sequence if condition]

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 the for…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:

value = 123
print(value, 'is', 'even' if value % 2 == 0 else 'odd')
4/5/2019 3:16:26 AM

One way:

def change(f):
    if f is None:
        return unicode(f.strip())
        return ''

row = [change(x) for x in row]

Although then you have:

row = map(change, row)

Or you can use a lambda inline.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow