Q:

Python list comprehensions misunderstanding

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?

A:

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

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)]
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.

