I was wondering what is the best way (in Python) to iterate over sections from a list of a given size.
Say, for example, we have a list [1,2,3,4,5]and we want sections k=3. A bad way to do this is to write:
lst = [1,2,3,4,5]
for i in range(1,len(lst)):
for j in range(i+1, len(lst)):
print lst[:i], lst[i:j], lst[j:]
This gives
[1], [2], [3,4,5]
[1], [2,3], [4,5]
...
[1,2,3], [4], [5]
But if I later wanted to iterate over sections k=4, then I would have to add a level for nesting loops, which cannot be done at runtime. Ideally, I would like to write something like:
for part in partitions([1,2,3,4,5], k):
print part
Does anyone know a better way to do this?