Search code examples
pythonlistsublist

Split a list into sub lists of decreasing size


Suppose I have a list as

list = [0,1,2,3]

How would I split the lists into something like

new_list = [[0,1,2,3],[1,2,3],[2,3],[3]]

I've tried using:

def change(list):
    new_list = []
    for i in range(len(list)):
        total += [list:]
    return new_list

but I get a return value of

 new_list = [0,1,2,3,1,2,3,2,3,3]

Help would be greatly appreciated, thanks.


Solution

  • Use a simple list comprehension, which iterates over the length of original list. Also, I have used variable name lst, since list is a python type.

    Here you go:

    >>> lst = [0,1,2,3]
    >>> [lst[i:] for i in range(len(lst))]
    [[0, 1, 2, 3], [1, 2, 3], [2, 3], [3]]