Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this python generator function running correctly only once?

This is almost certainly a result of my ignorance of how generators work, but I am completely lost.

If I interactively create the following generator:

def neighborhood(iterable):
    iterator = iter(iterable)
    prev = None
    item = next(iterator) 
    for post in iterator:
        yield (prev,item,post)
        prev = item
        item = post
    yield (prev,item,None)

and then test it like:

for prev,item,next in neighborhood([1,2,3,4,5]):
print(prev, item, next)

It produces:

None 1 2
1 2 3
2 3 4
3 4 5
4 5 None

as expected. If I run it again, or try to redefine it in any way, I get a

'NoneType' object is not callable"

error.

like image 903
WildGunman Avatar asked Feb 17 '26 14:02

WildGunman


1 Answers

When you did

for prev,item,next in ...
#             ^^^^

you shadowed the built-in next function. The next time you try to use your generator, it fails because it gets your next variable instead of the function it needed.

like image 84
user2357112 supports Monica Avatar answered Feb 19 '26 05:02

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!