Generator using item[n-1] + item[n] memory

Chris Angelico rosuav at gmail.com
Sat Feb 15 08:41:25 CET 2014


On Sat, Feb 15, 2014 at 6:27 PM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Fri, Feb 14, 2014 at 8:31 PM, Nick Timkovich <prometheus235 at gmail.com> wrote:
>> OK, now the trick; adding `data = None` inside the generator works, but in
>> my actual code I wrap my generator inside of `enumerate()`, which seems to
>> obviate the "fix".  Can I get it to play nice or am I forced to count
>> manually. Is that a feature?
>
> Yeah, looks like enumerate also doesn't release its reference to the
> previous object until after it gets the next one.  You'll just have to
> make do without.

You could write your own enumerate function.

def enumerate(it, i=0):
    it = iter(it)
    while True:
        yield i, next(it)
        i += 1

That shouldn't keep any extra references around.

ChrisA



More information about the Python-list mailing list