Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to use *= python operator in list comprehension [duplicate]

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
like image 430
DanielSon Avatar asked Sep 11 '26 17:09

DanielSon


1 Answers

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.

like image 133
Curtis Lusmore Avatar answered Sep 13 '26 07:09

Curtis Lusmore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!