[Tutor] when is a generator "smart?"

Jim Mooney cybervigilante at gmail.com
Sun Jun 2 07:14:16 CEST 2013


On 1 June 2013 21:20, Steven D'Aprano <steve at pearwood.info> wrote:
> On 02/06/13 13:58, Jim Mooney wrote:
>>
>> It's a little unclear to me where generators are more efficient.
>
>
> When there are a lot of items, and you access the items one at a time, not
> all at once. If there are only a few items, a list or tuple has less
> overhead and is easier to use.

So how does one access a generator one element at a time? I thought
next would do that so I tried:

print(next(uneven_squares(10,1000)))
print(next(uneven_squares(10,1000)))
print(next(uneven_squares(10,1000)))

But I got the same answer every time. I'm just trying to see where a
generator is more beneficial in practice and exactly how one accesses
one element at a time without building a list.

Jim


More information about the Tutor mailing list