I'm not sure why I'm unable to use the *= operator in a list comprehension, when using it in a for loop is fine?
def funcLC(l):
ans = 1
[ans *= x for x in l if x < 0]
return ans
SyntaxError: invalid syntax
def funcFor(l):
ans = 1
for x in l:
if x < 0:
start *= x
return ans
The assignment operator (and all variations on it) forms a statement in Python, not an expression. Unfortunately, list comprehensions (and other comprehensions, like set, dictionary and generators) only support expressions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With