next returns the instance method of the iterator in python
- 2021-08-28 20:23:45
- OfStack
In python, there are many methods for set iteration. We call another loop after the program runs iteration, and every loop can be regarded as an iteration. Then after the iteration, we need to use the next function to return to the iterator. Next, we will show you the usage, parameters and return values of next and the example of returning iterators in python.
1. Usage of next ()
next(iterator[, default])
2. Parameter description
iterable--Iterable Objects
default--Optional to set the default value to be returned if there is no next 1 element. If not, an StopIteration exception will be triggered if there is no next 1 element.
3. Return value
Returns the next 1 item.
4. Examples
class test():
def __init__(self,data=1):
self.data = data
def __next__(self):
if self.data > 5:
raise StopIteration
else:
self.data+=1
return self.data
t = test(3)
for i in range(3):
print(t.__next__())
Output:
4
5
6
Usage of Python Iterator
Usage of iterators:
First of all, let's talk about two concepts, one is an iterable object, the other is an iterator object, and the two are different
Iterative (Iterable): That is, data can be retrieved by for loop, such as dictionaries, lists, tuples, strings, etc., and next () method cannot be used.
Iterator (Iterator), which is also an object that can iterate out data in turn, is stored in memory space as follows: < list_iterator object at 0x01E35770 > It occupies less memory and can use next () method to fetch data in turn
You can use the isinstance () method to determine whether an object is an iterable object or an iterator object
For example:
>>> a = [x for x in range(3)] # Generate 1 List
>>> from collections import Iterable # Import Iterable Module
>>> isinstance(a,Iterable) # Use isinstance( " ,Iterable) Determine whether it is iterative
True # Return True
>>> from collections import Iterator # Import Iterator Module
>>> isinstance(a,Iterator) # Use isinstance( " ,Iterator) Determine whether it is an iterator object
False # Return False
From the above results, it can be seen that the list is an iterative object, but not an iterator, and the same dictionaries, tuples and strings are not iterators. In addition, numbers are neither iterator objects nor iterative objects.