no.email at nospam.invalid
Fri Apr 3 08:46:42 CEST 2015
albert at spenarnc.xs4all.nl (Albert van der Horst) writes:
> You should give an example of usage. As a newby I'm not up to
> figuring out the specification from source for
> something built of the mysterious __ internal
In reality because of generator expressions, the yield statement, and
some useful built-in generators in the itertools module, you rarely
have to use those special methods.
I'd advise reading through the itertools module documentation from
beginning to end, trying to understand what everything does. Even if
some are not that useful, it will help convey the mode of thinking that
went into these features.
At a somewhat deeper level you might like the SICP book:
It's somewhat old now and it's about Scheme rather than Python, but it
builds up the relevant concepts quite nicely.
Regarding the squares example, consider this even simpler generator:
n += 1
so count(1) yields 1, 2, 3, 4 ...
This is a very useful generator but you don't need to write it since
it's included in the itertools module as itertools.count. Its initial
value defaults to 0. So the squares generator can be written:
return (i*i for i in itertools.count(0))
Now if you want all the squares less than 100 (i.e. 0, 1, 4, 9, ..., 81):
wanted = itertools.takewhile(lambda x: x<100, squares())
You can print that out as a list:
The built-in sum function consumes an iterator, so you can add up the
squares less than 100:
print(sum(itertools.takewhile(lambda x: x<100, squares())))
this prints 205 which is 1+4+9+16+25+36+49+64+81.
These features fit together quite elegantly and code like this flows off
the fingertips naturally once you've used to it.
More information about the Python-list