0

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.

2 Answers 2

1

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]]
>>>
Sign up to request clarification or add additional context in comments.

Comments

0

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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.