Split a list into sub lists of decreasing size

221 views Asked by At

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.

4

There are 4 answers

1
Anshul Goyal On BEST ANSWER

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]]
1
vks On
newlist=[]
list = [0,1,2,3]
i=0
while i<len(list):
    newlist.append(list[i:])
    i=i+1

print newlist
3
Vishnu Upadhyay On

You can also use map with lambda

 In [14]: map(lambda x: list[x:], xrange(len(list)))
 Out[14]: [[0, 1, 2, 3], [1, 2, 3], [2, 3], [3]]
0
Abhijeet On

See this

from itertools import islice

# Input list 
List1 = [1,2,3,4,5,6,7,8,9,10,11]

# [1,2,3,4],[5,6,7],[8,9],[10],[11]
length_to_split = [4, 3, 2, 1, 1]

# Using islice
X = iter(List1)
sublists = [list(islice(X, elem)) for elem in length_to_split]


print("Sublists : ", sublists)

output :

Sublists :  [[1, 2, 3, 4], [5, 6, 7], [8, 9], [10], [11]]

Reference: https://docs.python.org/3/library/itertools.html