The opposite of list flattening.
Given a list and a length n return a list of sub lists of length n.
def sublist(lst, n):
sub= ; result=
for i in lst:
if len(sub)==n: result+=[sub] ; sub=
if sub: result+=[sub]
[[1, 2, 3], [4, 5, 6], [7, 8]]
Such a list of lists could be constructed using a list comprehension:
In : seq=[1,2,3,4,5,6,7,8] In : [seq[i:i+3] for i in range(0,len(seq),3)] Out: [[1, 2, 3], [4, 5, 6], [7, 8]]
There is also the grouper idiom:
In : import itertools In : list(itertools.izip_longest(*[iter(seq)]*3)) Out: [(1, 2, 3), (4, 5, 6), (7, 8, None)]
but note that missing elements are filled with the value None. izip_longest can take a
fillvalue parameter as well if something other than None is desired.
list1+=[list2] -- noting the brackets this time -- is equivalent to
list1.append(list2). My highest priority when writing code is readability,
not speed. For this reason, I would go with
list1.append(list2). Readability is subjective, however, and probably is influenced greatly by what idioms you're familiar with.
Happily, in this case, readability and speed seem to coincide:
In : %timeit list1=[1,2,3]; list1.append(list2) 1000000 loops, best of 3: 612 ns per loop In : %timeit list1=[1,2,3]; list1+=[list2] 1000000 loops, best of 3: 847 ns per loop