Welcome, guest | Sign In | My Account | Store | Cart

The opposite of list flattening.

Given a list and a length n return a list of sub lists of length n.

Python, 7 lines
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.

1 comment

Michael Puckett (author) 13 years, 4 months ago  # | flag

Ha! Guess this is trivial using a list comprehension:

Given:

lst = [1,2,3,4,5,6,7,8]
n   = 3

Then:

[lst[i:i+n] for i in range(0,len(lst),n)]

Returns:

[[1, 2, 3], [4, 5, 6], [7, 8]]

Note to self: conquer list comprehensions.

Created by Michael Puckett on Tue, 21 Dec 2010 (MIT)
Python recipes (4591)
Michael Puckett's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks