[Python-ideas] Introduce collections.Reiterable
Steven D'Aprano
steve at pearwood.info
Thu Sep 19 14:28:30 CEST 2013
On Thu, Sep 19, 2013 at 06:31:12AM -0400, Terry Reedy wrote:
> On 9/19/2013 4:59 AM, Neil Girdhar wrote:
> >Well, generators are iterable, but if you write a function like:
> >
> >def f(s):
> > for x in s:
> > do_something(x)
> > for x in s:
> > do_something_else(x)
>
> This strikes me as bad design. It should perhaps a) be two functions or
> b) take two iterable arguments or c) jam the two loops together.
Perhaps, but sometimes there are hidden loops. Here's an example near
and dear to my heart... *wink*
def variance(data):
# Don't do this.
sumx = sum(data)
sumx2 = sum(x**2 for x in data)
ss = sumx2 - (sumx**2)/n
return ss/(n-1)
Ignore the fact that this algorithm is numerically unstable. It fails
for iterator arguments, because sum(data) consumes the iterator and
leaves sumx2 always equal to zero.
--
Steven
More information about the Python-ideas
mailing list