Search code examples
pythonlistsublist

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.


Solution

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