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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
For your
each_cons
function, try this out:That will get you an iterator over groups of
n
consecutive elements initerable
. 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.