Improving the all_equal recipe in itertools doc

It may just be a personal preference, but I would like to avoid the double negative not False in favor of just True. If that costs a slight inefficiency in the single case of an empty input, I’m fine with that. Also, I prefer the positively worded docstring which matches the style used in the builtin all() function.

If the slight inefficiency bugs you, consider submitting a PR to the more-itertools project. Those tools are more about being used (where speed matters) rather than being read (where topic focus matters). I’ve done this myself for convolve where the beautiful version in the docs isn’t as fast as what I submitted to more-itertools with sliding_window inlined and the unneeded tuple conversion removed.

To the other respondents to the thread. Yes, there are many ways to implement all_equal(). We had a nice Twitter thread competition on the subject and I summarized some of the results in a StackOverflow answer. For a list input, my favorite was t.count(t[0]) == len(t). For purposes of the itertools recipes though, the groupby() variant is preferred because 1) it teaches you something about groupby which is the least obvious itertool, 2) it works with iterator inputs, 3) is memory efficient, 4) relies only on equality tests rather than hashing or sorting, 5) runs at C speed, 6) doesn’t use auxiliary memory or a counter, 7) demonstrates a functional style characteristic of itertools, 8) has an early-out. Mostly though, I like that it gets to the heart of what groupby is all about which is lazily chunking groups of equal values (much like the Unix uniq command line tool). That is actually the only reason the all_equal() recipe was included.

9 Likes