CF84 CF84 - 1 month ago 5
Python Question

Python: slicing a list into a list of lists using list comprehension

I have a simple list like this:

mylist=[0,1,2,3,4,5,6,7,8,9]


which I want to slice creating a list of lists. The intended outcome is:

sliced=[[0],[0,1],[0,1,2],[0,1,2,3],...]






  1. First attempt:
    sliced=[mylist[i:i+n] for i in range(0, len(mylist), n)]


    wrong result:
    sliced=[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]







  1. Second attempt:
    sliced=[[mylist[l]] for l in range(0,10,1)]


    wrong result:
    sliced=[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]






How should I handle this?

Answer

Like this?

>>> mylist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> sliced = [mylist[0:i] for i in range(1, len(mylist) + 1)]
>>> sliced
[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]


Further reading: Explain Python's slice notation