Append cumulative list of lists python

Question:

I am trying to extend a list of lists in a commulative way like this:

# Consider the following list of lists
l_Of_l = [ [1], [2], [3], [4], [5], [6], [7]]

Desired result is:

l_extended = [ [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7]]

So basically the size of the list remains the same after extending commulatively.

Edit:

Here is what I did initially:

l_Of_l = [ [1], [2], [3], [4], [5], [6], [7]]
lista = []
for i in l_Of_l:
    lista.extend(i)
    print(list([i for i in lista]))

But then the result was:

[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]

Does anyone know how to achieve this in the correct way?

Asked By: tavalendo

||

Answers:

Use accumulate from itertools:

list(itertools.accumulate(l_Of_l))                                                                                              
Out: 
[[1],
 [1, 2],
 [1, 2, 3],
 [1, 2, 3, 4],
 [1, 2, 3, 4, 5],
 [1, 2, 3, 4, 5, 6],
 [1, 2, 3, 4, 5, 6, 7]]
Answered By: kantal

You want a cumulative sum, just with lists. itertools.accumulate can do this.

>>> from itertools import accumulate
>>> lst = [[1], [2], [3], [4], [5], [6], [7]]
>>> list(accumulate(lst))
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7]]
Answered By: timgeb

You can also create a simple list comprehension:

>>> from operator import itemgetter
>>> l_Of_l = [[1], [2], [3], [4], [5], [6], [7]]
>>> [list(map(itemgetter(0), l_Of_l[:i+1])) for i in range(len(l_Of_l))]
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7]]
Answered By: RoadRunner

One way to do this without itertools is to use Python’s sum function to concatenate lists.

>>> L =  [ [1], [2], [3], [4], [5], [6], [7] ]
>>> L_extend = [ sum(L[0:i+1], []) for i in range(len(L)) ]
Answered By: Bill M.
 lol =  [ [1], [2], [3], [4], [5], [6], [7] ]
 lol_test = [[*range(1, i+2)]for i in range(len(lol))]
 print(lol_test)

I came up with a solution similar to Bill M, just a small difference. I am just a novice learning python.

And it worked with the same output: [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7]]

Answered By: J_Ken
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.