Here is a very simple code:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = 1
c = [b*=i for i in a]
print(c)
I am trying to multiply all of the numbers in the list a, but I get a syntax error for line 3. How can I fix the code?
Here is a very simple code:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = 1
c = [b*=i for i in a]
print(c)
I am trying to multiply all of the numbers in the list a, but I get a syntax error for line 3. How can I fix the code?
=
and the augmented versions like it aren't expressions that evaluate to a value. The issue is, that's what list comprehensions are expecting: an expression.
The comprehension consists of a single expression followed by at least one for clause and zero or more for or if clauses.
To do this, you'd need Python 3.8 and assignment expressions:
[b := b * i for i in a]
There is no augmented version that combines *
and :=
.
Consider just using a full loop though.
Another option for this is the following:
import operator
from functools import reduce
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = reduce(operator.mul, a, 1)
print(b)
By the way, this was referenced in this question:
What's the function like sum() but for multiplication? product()?
EDIT: As noted by @ShadowRanger, starting in Python 3.8 you could simplify this to:
import math
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = math.prod(a)
print(b)
As mentioned in the comments, you can't do item assignment inside of a list comprehension. What you could do is
b=1
for x in a:
b*=x
print(b)