[issue38200] Adding itertools.pairwise to the standard library?

Tim Peters report at bugs.python.org
Wed Sep 18 15:15:56 EDT 2019


Tim Peters <tim at python.org> added the comment:

There's an eternal culture clash here:  functional languages have a long history of building in just about everything of plausible use, regardless of how trivial to build on other stuff.  This started when LISP was barely released before (cadr x) was introduced as a shorthand for (car (cdr x)), and (caddr x) for (car (cdr (cdr x))), and so on.  Which more modern functional languages also supply (second x) and (third x) spellings for (_and_ nth(2, x) and nth(3, x) spellings).

This one is harder to get right than those, but not hard at all.  But it's not coincidence that itertoolz[1] (note the trailing 'z') also supplies it, spelled `sliding_window(width, iterable)` there.  Working with finite difference algorithms is probably "the most obvious" use case for a width of 2.

More esoterically, one of my favorite "technical indicators" for stock analysis is a dead simple 20-period simple moving average, which can be built very conveniently (although not very efficiently - but I don't usually care) by mapping a mean function over a sliding window of width 20.

BTW, if you want padding on each end, you can apply pairwise to `chain([first], iterable, [last])`.

A related function is breaking an iterable into _non_-overlapping chunks of a given width.  itertoolz spells that "partition".  For me that comes up more often than overlapping windows.

I like having these things around, but it's not a big deal.  Perhaps it would be an easier decision in Python if we gave up on believing that everything in itertools _must_ be coded in C.  In functional idioms sometimes speed isn't the point at all, but rather using conventional names for simple but compound functionality.  Like that "sliding window" is a concept in its own right.  If I'm _picturing_ an algorithm in terms of a sliding window, then - of course - the shortest distance to working code is to use a facility that already implements that concept.

Which is a long way of saying +0.

[1] https://toolz.readthedocs.io/en/latest/api.html

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue38200>
_______________________________________


More information about the Python-bugs-list mailing list