1

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?

1
  • 2
    you could make it a list comprehension ... but other than being a more pythonc one liner there isnt much benifit Commented Nov 12, 2015 at 23:53

1 Answer 1

4
>>> l = [1, 2, 3, 4]
>>> [l[:i+1] for i in range(len(l))]
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
Sign up to request clarification or add additional context in comments.

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.