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)]
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.