Serg Melikyan Serg Melikyan - 3 months ago 9
Python Question

How to split python list into chunks of equal size?


Possible Duplicate:

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

python: convert “5,4,2,4,1,0” into [[5, 4], [2, 4], [1, 0]]




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


->

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


Are there simple way to do it, without explicit 'for'?

Answer
>>> x = [1,2,3,4,5,6,7,8,9]
>>> zip(*[iter(x)]*3)
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

How does zip(*[iter(s)]*n) work in Python?

Comments