0

Possible Duplicate:
How do you split a list into evenly sized chunks in Python?

I have a list of n elements and I want to split them evenly into sub-lists.

Desired interaction

>>>func([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)
[[1,2,3], [4,5,6], [7,8,9]]

I would just assume x divides into n evenly.

Fastest way to do this? My current version is as follows:

def func(L, x):

    newL = []
    for i in range(len(L) // x):
        subL = []
        for j in range(x):
            subL.append(L.pop(0))
        newL.append(subL)
    return newL
Community
  • 1
  • 1
MxLDevs
  • 19,048
  • 36
  • 123
  • 194

0 Answers0