[Tutor] when is a generator "smart?"

Steven D'Aprano steve at pearwood.info
Sun Jun 2 08:17:44 CEST 2013


On 02/06/13 15:14, Jim Mooney wrote:
> 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.

That's because you create three independent generators, one after another.

it = uneven_squares(10,1000)  # "it" for "iterator"
print(next(it))
print(next(it))
print(next(it))


You can also use the itertools module to slice a generator:

list(itertools.islice(it, 5, 10, 2))

This call to islice will grab the 5th, 7th and 9th items from it, *starting at the current position*, and return an iterator. The call to list() converts that iterator to a list, so you can easily inspect the values. Here's an example:

py> it = iter("abcdefghijklmnopqrstuvwxyz")
py> next(it)
'a'
py> next(it)
'b'
py> list(itertools.islice(it, 5, 10, 2))
['h', 'j', 'l']
py> next(it)
'm'



-- 
Steven


More information about the Tutor mailing list