-3

Generally, whenever I do a for loop in python, I try to convert it into a list comprehension. Here, I have a for loop where a variable value is altered after each loop.

k=5
for x in range(1,6):
    k*=x
    print(k)
#output
5
10
30
120
600

I want to perform this operation in list comprehension. I tried doing but I was getting syntax error. I tried this below:

[k*=x for x in range(1,6)]
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
  • You might need a reduce instead of a list. List comprehension is not a replacement of loops. List comprehension is a construction of a list. If you can use standard library `math`, `k = math.prod(range(1, 6), start=5)` will work. Or you can use `functools.reduce`. `functools.reduce(operator.mul, range(1, 6), 5)` – Boseong Choi Oct 18 '22 at 05:59
  • 4
    Don't use list comprehensions for side effects, that's not at all what they are meant for. – Thierry Lathuille Oct 18 '22 at 06:00
  • There is a walrus operator introduced in Python 3.8. Your solution would be `[k := k*x for x in range(1,6)]`. You can also update your `for` loop using it – Igor Voltaic Oct 18 '22 at 06:12

1 Answers1

2

You can use walrus operator (python 3.8+):

k = 5
output = [k := k * x for x in range(1, 6)]

print(output) # [5, 10, 30, 120, 600]

But this pattern is not welcomed by some people.

Another option would be to use itertools.accumulate:

from itertools import accumulate
from operator import mul

output = accumulate(range(1, 6), mul, initial=5)

print(*output) # 5 5 10 30 120 600

In this case the initial value 5 is attached at the beginning.

j1-lee
  • 13,764
  • 3
  • 14
  • 26