In python there are a number of methods for iterating over a collection, we call the loop after the program is run an iteration, and every time we loop can be seen as an iteration. So at the end of the iteration, we need to use the next function to return to the iterator. Next we use next, parameters, return value, return to the iterator in python examples to show you.
(usage
next(iterator[, default])
2. Description of parameters
iterable -- iterable objects
default -- Optional, set the default value to be returned if there is no next element, if not set and there is no next element then a StopIteration exception will be triggered.
3. Return Value
Return to the next item.
4. Examples
class test(): def __init__(self,data=1): = data def __next__(self): if > 5: raise StopIteration else: +=1 return t = test(3) for i in range(3): print(t.__next__())
Output:
4
5
6
Usage of Python Iterators
Iterator usage:
Let's start with two concepts.One is an iterable object,One is an iterator objectTwo different
Iterable:That is, you can for loop to fetch data, such as dictionaries, lists, tuples, strings, etc., you may not use the next() method.
Iterator.It is also an object that can iterate through the data sequentially, and is stored in the memory space like this: <list_iterator object at 0x01E35770> occupies a small amount of memory and can be used to take the data sequentially using the next() method.
You can use the isinstance() method to determine whether an object is an iterable or iterator object
For example:
>>> a = [x for x in range(3)] # Generate a list >>> from collections import Iterable # Import the Iterable module >>> isinstance(a,Iterable) # Use isinstance("",Iterable) to determine whether it is iterable or not True # Returns True >>> from collections import Iterator #Import the Iterator module >>> isinstance(a,Iterator) # Use isinstance("",Iterator) to determine if it is an iterator object False # Returns False
As you can see from the results above, a list is an iterable object but not an iterator, similarly dictionaries, tuples, strings are not iterators, also numbers are neither iterator objects nor iterables.
to this article on next in python to return the iterator of the example method of the article is introduced to this, more related to next how to return the iterator in python content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!