Somz
Somz

Reputation: 43

Creating sequential sublists from a list

I'm new here and to programming as well.

I don't know if I put the question right, but I have been trying to generate sublists from a list.

i.e

say if L = range(5), generate sublists from L as such [[],[0],[0,1],[0,1,2],[0,1,2,3],[0,1,2,3,4]].

Kindly assist. Thanks.

Upvotes: 0

Views: 516

Answers (2)

praba230890
praba230890

Reputation: 2310

You can also generate the sublists you've asked for by using the below for loop.

>>> L = range(5)
>>> l = []
>>> for i in range(len(L)+1):
        l.append([j for j in range(i)])
>>> l
[[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4]]

Also you can create the sublists without an empty sublist as the starting sublist through the code:

>>> i = list(range(5))
>>> [i[:k+1] for k in i]
[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4]]

Upvotes: 0

user2555451
user2555451

Reputation:

Look at this:

>>> # Note this is for Python 2.x.
>>> def func(lst):
...     return map(range, xrange(len(lst)+1))
...
>>> L = range(5)
>>> func(L)
[[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4]]
>>>

Upvotes: 1

Related Questions