Search code examples
pythonpython-2.7python-itertools

Generate following subsets from list in efficient/pythonic manner


From the list [1,2,3,4] I would like to get [[1],[1,2],[1,2,3],[1,2,3,4]]. I'm not sure what this is called (if anything), perhaps something like following subsets?

My current approach is:

def following_subsets(parts):
    following_subsets = []
    for i in range(1, len(parts)):
        following_subsets.append(parts[:-i])
    return following_subsets

Is there a more efficient way of doing this, or a more pythonic way? Perhaps utilising iterators in some fashion?


Solution

  • >>> l = [1, 2, 3, 4]
    >>> [l[:i+1] for i in range(len(l))]
    [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]