Thursday, 29 April 2021

Conditions in list comprehensions. Why is it different when I use 'else'?

Code A:

numbers = [2, -1, 79, 33, -45]
negative_doubled = [num * 2 for num in numbers if num < 0]
print(negative_doubled) # output is: [-2, -90]

Code B:

numbers = [2, -1, 79, 33, -45]
doubled = [num * 2 if num < 0 else num * 3 for num in numbers ]
print(doubled) # output is: [6, -2, 237, 99, -90]

As you can see the position of the if statements are different. In code A, the if statement positioned after the for loop statement.

Why don't they write the code like this? I would find it more intuitive.

numbers = [2, -1, 79, 33, -45]
negative_doubled = [num * 2 if num < 0 for num in numbers] # SyntaxError
print(negative_doubled) 

(As you know this placement is a syntax error.)

Is there any case where it could be a problem?



from Conditions in list comprehensions. Why is it different when I use 'else'?

No comments:

Post a Comment