What is wrong with this ?

threes_and_fives=[x if (x%3==0 or x%5==0) for x in range(1,16)]

What is wrong with this ?

threes_and_fives=[x if (x%3==0 or x%5==0) for x in range(1,16)]

Error is

File "python", line 1

threes_and_fives=[x if ((x%3==0) or (x%5==0)) for x in range(1,16)]

^

SyntaxError: invalid syntax

*List Comprehension syntax example:*

`even_squares = [x**2 for x in range(1,11) if ( x % 2) == 0]`

Pay attention to the order, that is the key aspect of list comprehension.

we have normal list comprehension:

`squares = [x for x in range(5)]`

then we have list comprehension + if:

`squares = [x for x in range(5) if x % 4 == 0]`

then we have if else:

`squares = [x if x % 4 == 0 else 0 for x in range(5) ]`

if you only have an `if`

, it should be at the end of your list comprehension

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.