3

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
DanielSon
  • 1,415
  • 4
  • 27
  • 40
  • 3
    List comprehensions are not just the cool kids' way of writing loops. They're for *building lists*. If you aren't trying to build a list, list comprehensions are not the tool for the job. – user2357112 Sep 22 '16 at 23:48
  • I didn't know that before, and now I do, so thanks. – DanielSon Sep 23 '16 at 02:30

2 Answers2

6

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.

Curtis Lusmore
  • 1,822
  • 15
  • 16
3

Alternatively, you can approach it with reduce() and filter():

>>> from operator import mul
>>> from functools import reduce  # needed if Python 3.x
>>>
>>> l = [-1, 2, 4, 1, -3]
>>> reduce(mul, filter(lambda x: x < 0, l), 1)
3

A related tip: one of the indicators for using reduce() is that you have multiple values, but need to produce a single value out of it.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195