How to use an iterator?

Rob Gaddi rgaddi at technologyhighland.invalid
Mon Jun 1 21:34:37 EDT 2015


On Mon, 01 Jun 2015 18:26:57 -0700, fl wrote:

> Hi,
> 
> 
> I read the online tutorial on iterator:
> 
> https://docs.python.org/2/library/itertools.html
> 
> I have no idea on how to use this one:
> 
> itertools.count(start=0, step=1)
> 
> BTW, I am using Python 2.7.9 on Windows 7.
> 
> 
> 
> I even input the following:
> 
> def count(start=0, step=1):
>     # count(10) --> 10 11 12 13 14 ... # count(2.5, 0.5) -> 2.5 3.0 3.5
>     ...
>     n = start while True:
>         yield n n += step
> 
> 
>>>> xc=count(10)
>>>> xc
> <generator object count at 0x02BA9AD0>
> 
> 
> How to use this generator?
> 
> 
> Thanks,

Like this:

for xc in count(10):
    print(xc)

Then you hit Ctrl-C to kill the program because your generator is 
infinite, but the principle is sound.

Infinite iterators are of limited, but non-zero, use.  Generally you use 
them with some other function performing the bounding, such as:

for n, xc in zip(range(10, 0, -1), count(10)):
    print(n, xc)

range is a generator, similar to your count, but it's finite.  It'll 
output the numbers 10 through 1 in descending order.

zip is also a generator; it takes from each iterator input, bundles them 
together, and returns a tuple of all the inputs, until any one of the 
input iterators is exhausted.  Since range is finite, the zip becomes 
finite, and the infinitude of your generator isn't an issue.

You could of course turn this on its head and ask for

for n, xc in zip(count(0), someotheriterable):
    print(n, xc)

And use your count infinite iterator to enumerate the (hopefully finite) 
elements of someotheriterable.  This is common enough that the built-in 
enumerate function does exactly that.

Make sense yet?

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.



More information about the Python-list mailing list