2

There is seems to be something wrong with this example:

item = [x**2 if x %2 == 0 for x in range(10)] 

But I can write like that:

item = [x**2 if x % 2 == 0 else x**3 for x in range(10)] 

Or:

item = [x**2 for x in range(10) if x % 2 == 0] 

How important is the order here and why I can't use 'if' without 'else' in the first example?

2 Answers 2

5

There are two different, unrelated uses of the if keyword here:

  1. As part of a conditional expression, of the form ... if ... else ...:

    item = [x**2 if x % 2 == 0 else x**3 for x in range(10)]
  2. As the filter for a list comprehension, of the form if ...:

    item = [x**2 for x in range(10) if x % 2 == 0]

In your first example, you have a malformed conditional expression that is missing its else. Further, the semantics are different. In 1), you get some value in the list for every value in range(10). In 2), you only get a value in the list for the even values.

Sign up to request clarification or add additional context in comments.

Comments

1

That happens because if you put the if in the first part, that defines the value, and the if is considered a ternary operator.

This means that you cannot have it without an else, just like you can't write

item = 2 if other_item == 3

Because the right side is evaluated to... what, when the other_item is not 3?

So, you need something like

item = 2 if other_item == 3 else 4

Your example is the same.

If you instead have it at the end, that's a conditional that excludes the value entirely, so you are not expected to have an alternative: you're basically saying "don't include this value in the results".

1 Comment

Thanks. Now I understand.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.