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:
for i in xrange(0, len(ints), 4):
# dummy op for example code
foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3]
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?
while ints:
foo += ints[0] * ints[1] + ints[2] * ints[3]
ints[0:4] = []
Still doesn't quite "feel" right, though. :-/
Related question: How do you split a list into evenly sized chunks in Python?
Simple. Easy. Fast. Works with any sequence:
Similar to other proposals, but not exactly identical, I like doing it this way, because it's simple and easy to read:
This way you won't get the last partial chunk. If you want to get
(9, None, None, None)
as last chunk, just useizip_longest
fromitertools
.I like this approach. It feels simple and not magical and supports all iterable types and doesn't require imports.
Another way:
Modified from the recipes section of Python's itertools docs:
Example
In pseudocode to keep the example terse.
Note:
izip_longest
is new to Python 2.6. In Python 3 usezip_longest
.Since nobody's mentioned it yet here's a
zip()
solution:It works only if your sequence's length is always divisible by the chunk size or you don't care about a trailing chunk if it isn't.
Example:
Or using itertools.izip to return an iterator instead of a list:
Padding can be fixed using @ΤΖΩΤΖΙΟΥ's answer: