Next () scope in Python

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

The code I use looks something like this:

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

Please note that I am using Python 3.2.

+6
source share
3 answers

You can use __builtins__.next to reference the built-in next 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.

+10
source

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

 desired_value = value_iterator.next() 

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

+6
source

Before assigning something to the following, use something like:

 real_next = next 
+2
source

Source: https://habr.com/ru/post/920375/


All Articles