Search code examples
pythonpython-3.xlistlist-comprehensionsequence

printing out a sequence using list comprehension instead of for loop


Using python,I want to generate a sequence [0,2,6,12,20,30,42,56,72,90]; The logic that I've figured out is like this

i,j =0,0
for i in range(1,10):
j+= 2*i
print(j)

Instead of for loop, I need to generate the same using list comprehension and I've tried my best to do so, but in the end no result. I've tried using this

j =[0]
j = [j[i-1] + 2*i for i in range(1,10)]

and I ended up getting list out of index error, rightfully so. I've no clue how to do this; Hence I'm here. Can anyone help me out? P.S. I don't want to rely on any generative AI tools for this problem.


Solution

  • List comprehensions can't access their previous result, so a list comprehension isn't ideal here without some hacks. What is ideal is itertools.accumulate:

    >>> from itertools import accumulate
    >>> list(accumulate(range(10), lambda j, i: j + 2 * i))
    [0, 2, 6, 12, 20, 30, 42, 56, 72, 90]