DEV Community

Discussion on: Each Pair with Itertools

Collapse
 
somacdivad profile image
David Amos • Edited

For your each_cons function, try this out:

def each_cons(n, iterable):
    iters = [iter(iterable)] * n
    return itertools.zip_longest(*iters)

That will get you an iterator over groups of n consecutive elements in iterable. No indexing or list building required!

This is basically the grouper function that can be found in the recipes section of the itertools docs.

You can also find it (and other examples of itertools goodness) in my write-up at realpython.com/python-itertools.

EDIT: I just looked at your requirements for each_cons again, and realized my function above isn't quite what you want.

For an example of what you're looking for, check out the windowed() function in the more-itertools package.

It's not built-in to Python, but you can look at the source. A bit more verbose than your solution, but for large iterables it's the way to go. Uses far less memory and will be way faster than using list slices.