A Python Generator to Generate Sublists of Increasing Length
Posted: July 17th, 2009 | Author: ryan | Filed under: Python, Tips and Tricks | View CommentsHere’s a nifty generator to take a list, l, of length n and get each of n sublists, l[0:i], where i ranges from 1 to n+1.
1 2 3 4 5 6 7 8 9 10 | def gen_sub_lists(l): """Generate sublists of a list. Sublists of [0,1,2,...,n] are [0], [0,1], [0,1,2], . . . , [0,1,2,...,n]. """ lengths = range(len(l)) for end in lengths: yield l[0:end+1] |




Leave a Reply