astay13
astay13

Reputation: 6927

Scope of next() in Python

I am trying to use the next function on an iterator, however, I have a local variable in the same scope that is also named next. The obvious solution is to rename the local variable, however, I'm fairly new to Python so I'm curious to learn how to prefix the next function so I achieve the desired behavior.

The code I'm using looks something like this:

for prev, curr, next in neighborhood(list):
    if (prev == desired_value):
        print(prev+" "+next)
        desired_value = next(value_iterator)

Note that I'm using Python 3.2.

Upvotes: 6

Views: 262

Answers (3)

kindall
kindall

Reputation: 184091

You can call the next() method of the iterator directly. You lose, however, the ability to suppress StopIteration at the end of the iteration in favor of seeing a default value.

desired_value = value_iterator.next()

Note that in Python 3, this method has been renamed __next__().

Upvotes: 6

user1277476
user1277476

Reputation: 2909

Before you assign something to next, use something like:

real_next = next

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 838006

You can use __builtins__.next to refer to the next built-in function.

for prev, curr, next in neighborhood(list):
    if (prev == desired_value):
        print(prev+" "+next)
        desired_value = __builtins__.next(value_iterator)

However, as you point out, the obvious solution is to use a different name for your variable.

Upvotes: 10

Related Questions