Skip to content
Advertisement

How to iterate over a list in chunks

I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don’t have control of the input, or I’d have it passed in as a list of four-element tuples. Currently, I’m iterating over it this way:

JavaScript

It looks a lot like “C-think”, though, which makes me suspect there’s a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn’t be preserved. Perhaps something like this would be better?

JavaScript

Still doesn’t quite “feel” right, though. :-/

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

Advertisement

Answer

Modified from the Recipes section of Python’s itertools docs:

JavaScript

Example

JavaScript

Note: on Python 2 use izip_longest instead of zip_longest.

Advertisement