0

I have question about list comprehension. If I want to output the odd squared numbers and put the condition in the output part (I know how to put condition in the loop part to get the desired result)

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

returned an error code. Why Python doesn't like it?

By adding else, the following returns zeros

[num**2 if num % 2==0 else 0 for num in range(10)]

so I tried to remove zeros on top of this

[num**2 if num % 2==0 else 0 for num in range(10)].remove(0)

and python returned empty, why?

bingzong88
  • 19
  • 3

2 Answers2

3
  1. [num**2 if num % 2==0 for num in range(10)] returned an error code. Why Python doesn't like it?

You have the list comprehension syntax backwards. The for comes first, then the if.

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

Alternatively, use range’s step parameter:

[num**2 for num in range(0, 10, 2)]
Ry-
  • 218,210
  • 55
  • 464
  • 476
0

The list comprehension is out of order.

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. -- Python, Data Structures Documentation, List Comprehensions

Change your first one to:

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

output:

[0, 4, 16, 36, 64]
Nathan
  • 3,082
  • 1
  • 27
  • 42