showkey
showkey

Reputation: 358

The if statement in a list comprehension

>>> row = [1,2,3,4,"--"]
>>> row = [cell.replace("--","hello") for cell in row if cell == "--"]
>>> row
['hello']

How can I get [1,2,3,4,"hello"] with a list comprehension?

Upvotes: 0

Views: 92

Answers (2)

BrenBarn
BrenBarn

Reputation: 251383

[cell.replace("--","hello") if cell=="--" else cell for cell in row]

When using the if at the end of the for, it restricts which items are considered, so that version will only return one item, since only one item in the source list matches the condition.

Also in this case you don't need to use replace, you could just use "hello" if cell=="--" instead, but you would use this form if you had multiple items you wanted to manipulate.

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121924

You'd use a conditional expression instead:

["hello" if cell == "--" else cell for cell in row]

This is part of the left-hand element-producing expression, not the list comprehension syntax itself, where if statements act as a filter.

The conditional expression uses the form true_expression if test_expression else false_expression; it always produces a value.

I simplified the expression a little; if you are replacing "--" with "hello" you may as well just return "hello".

Upvotes: 4

Related Questions