Loops list comprehension: Conditionals

Hey,

Sorry couldn’t find an explanation: why in the first case if is used after for:

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

and in the second case if is used before for

numbers = [2, -1, 79, 33, -45]
doubled = [num * 2 if num < 0 else num * 3 for num in numbers ]
print(doubled)

https://www.codecademy.com/courses/learn-python-3/lessons/learn-python-loops/exercises/list-comprehension

Sorry I’m a total beginner,

Thanks

2 Likes

When you are writing for loops in one line it should be written in this way. but in second example you added else statement thats why it comes before. There is no explanation when it comes to rules for a specific language but we can remember in that way.

1 Like

In the second example it’s not part of list comprehension syntax. It’s a different thing called “conditional expression”.

In a very simple way (please do not refer to my terms I just made them up for simplicity in this particular case) the structure of list comprehension goes like:
assignment expression - iteration (for) - filter (if)

In the second example the conditional expression is part of what I called “assignment expression”.

Before you ask. Why can’t you just replace them with each other? Well, you can’t have conditional expression without “else” and you can’t have a “filter” in list comprehension with “else”.

Hope it helps.

1 Like

Thank you both for your explanations, it’s clear and makes sense now !

if any of the replies have helped you then make one of answers identified as it s solved, it will help others to find out solution.

1 Like