Home > Software design >  Remove else statement from list comprehensions
Remove else statement from list comprehensions

Time:01-28

Why won't it not, not letting me use a else statement? When I run this code it's giving me this error SyntaxError: expected 'else' after 'if' expression, but I simply don't want to return anything after the if statement

x = ["x" if "x" in letter for letter in s]

CodePudding user response:

It looks like what you want to do is to filter the list, rather than to map each value to a different value. The syntax for that is to place an if clause at the end of the list comprehension:

["x" for letter in s if "x" in letter]

At this position in a list comprehension, if has a special meaning: the subsequent expression is used for filtering, so that the comprehension returns only those elements that satisfy the condition (and there can be no else). The condition is evaluated with the original value of the item, but you can still do mapping (as you do, since you're using "x" instead of letter).

In your original attempt, you used if in the mapping expression (which says what you want each result element to be). There, it is interpreted as a conditional expression that must have an else.

By the way, if s is a string, so that letter is a single-character string, you should use letter == "x" instead of "x" in letter. The latter works, but kinda by accident (because Python represents individual characters as strings with length one), and looks confusing because the right hand side of in is usually a "full" string or a collection.

CodePudding user response:

Two main parts of list comprehensions are : condition part and expression part.

Here is the syntax:

[expression for member in iterable if condition]

in condition part, you can not use else. Think of it as a filter. Move it to the end so that it acts like a filter:

x = ["x" for letter in s if "x" in letter]

But in expression part you can have any valid Python expression.

for example a conditional expression as the expression part which is:

a = <on_true> if <condition> else <on_false>

So you need to have the else part in expression part of the list comprehension because the expression part is indeed a conditional expression and the conditional expression need else.

  •  Tags:  
  • Related