The opposite of list flattening.
Given a list and a length n return a list of sub lists of length n.
1 2 3 4 5 6 7 | def sublist(lst, n):
sub=[] ; result=[]
for i in lst:
sub+=[i]
if len(sub)==n: result+=[sub] ; sub=[]
if sub: result+=[sub]
return result
|
An example:
If the list is:
[1,2,3,4,5,6,7,8]
And n is:
3
Return:
[[1, 2, 3], [4, 5, 6], [7, 8]]
Is there a more eloquent / concise way?
An aside, what is preferred when appending lists to lists (in the context above):
list1+=[list2]
Or:
list1.append(list2)
Given that (according to Summerfeild's 'Programming in Python 3) they are the same?
Thanks.
Ha! Guess this is trivial using a list comprehension:
Given:
Then:
Returns:
Note to self: conquer list comprehensions.