« Hillary's Bosnia Trip and the Fate of the World | Main | Video debunking McCain ads -- spread it. »

April 10, 2008

Comments

Dave Dash

Thanks for posting this... I was looking for an elegant way of partitioning python lists.

Eric Pavey

Thanks for the list comprehension info. I was looking for that solution exactly, thanks for posting it :)

Dale

Very nice.

Michael Powe

Elegant and uses the language the way it was meant to be used. I looked at the other items in the ActiveState cookbook and thought, "clunky! I just want a way to parse a long list into smaller lists of a given length."

Thanks for the insight.

mp

nagisa

As I've tried saying in comment section of Go Deh! blog (and failed), you can get behaviour of slicing and not loosing any items by using zip_longest function instead of zip.

nagisa

As I've tried saying in comment section of Go Deh! blog (and failed), you can get behaviour of slicing and not loosing any items by using zip_longest function instead of zip.

Tom Lynn
>>> seq = [1,2,3,4,5,6,7,8,9,10]
>>> pieces = 4
>>> m = float(len(seq))/pieces
>>> [seq[int(m*i):int(m*(i+1))] for i in range(pieces)]
[[1, 2], [3, 4, 5], [6, 7], [8, 9, 10]]
Gary

nagisa, thanks for the note about zip_longest, but I'm not sure what it is. Do you mean izip_longest from itertools? That gives a different result, because it puts the remainder items into a separate tuple, filled out out with Nones. Could be useful in some cases, so it's good to know about.


>>> items, chunk = [1,2,3,4,5,6,7,8,9, 10], 3
>>> list(izip_longest(*[iter(items)]*chunk))
[(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, None, None)]

Tom Lynn

Or an integer equivalent:


>>> n = len(seq)
>>> [seq[n*i//pieces:n*(i+1)//pieces] for i in range(pieces)]
[[1, 2], [3, 4, 5], [6, 7], [8, 9, 10]]

rodney

wonderful solution. thanks for sharing.

Roger Iyengar

Thank you for posting this. I had been looking for a way to do this, but everything else I found was how to generate chunks of size n, rather than n chunks.

List Splitter

Thanks for the post! It has no doubt helped many.

I realize the post is 10+ years old. Did you know numpy now has a function that does this?

Gary Robinson

Nope, didn't know that about the numpy function. Thanks for commenting, it's amazing to see this post still reaching anyone after 10+ years!

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment

Your Information

(Name and email address are required. Email address will not be displayed with the comment.)