Unable to use if statement before for loop in List Comprehension

Question:

my_list = []
for x in range(1,50):
    if x%3==0:
        my_list.append(x)
    else:
        pass
print(my_list)
[x for x in range(1,50) if x%3==0]

Above mentioned both codes are working fine. but the below code is giving me error.

[x if x%3==0 else pass for x in range(1,50)]

Error:
File "", line 1
    [x if x%3==0 else pass for x in range(1,50)]
                         ^
SyntaxError: invalid syntax

But according to the syntax of List Comprehension if we are using “if” before “for” then it should be a complete “if-else” statement

According to my knowledge, all 3 codes should yield same output. Can anyone help me in understanding why I’m getting this error?

I tried executing this code in Python-3.7.4 version.

Thanks in advance.

Answers:

pass is a statement, not an expression, so you can’t use it in a list comprehension.

Your first version, as you noted, works fine and is the right way to filter a list in a comprehension, so I’m not sure why you are looking to make it work with the incorrect syntax.

To be more explicit, if you were to replace pass by a valid expression, eg:

[x if x%3==0 else 0 for x in range(1,50)]

then this wouldn’t raise any errors. It just wouldn’t do what I think you want, as all the non-multiples of 3 would have become 0, rather than having been excluded. But that’s how list comprehensions (and map and filter, which are equivalent) work: something of the form [expr(x) for x in lst] will always have exactly the same length as lst, and in order to filter using an if statement you need the if clause after the for, as in your first, working, example.

Answered By: Robin Zigmond
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.