+ 5
`if` conditional goes before the loop range specification. list1= [ a ** 3 if a % 3 else a ** 2 for a in range( 3 ) ]
9th Jun 2022, 9:16 AM
Ipang
+ 4
When there is only one condition, we can put it at end of list comprehension construct. But if we have additional conditions e.g. specified in an `else` block, then we put the conditionals after the sub-expression that represents the value (here variable <a> either cubed or squared). https://realpython.com/list-comprehension-JUMP_LINK__&&__python__&&__JUMP_LINK/
9th Jun 2022, 10:16 AM
Ipang
+ 4
["Maziar","Dokhanian"] Because the condition applies to the list items - either a**3 or a**2, and not to the for loop. The loop must run free, then the items be subject to the if condition.
9th Jun 2022, 11:10 AM
Emerson Prado
Emerson Prado - avatar