"The Road to Python Learning--The Working Principle of Iterators and For Loops Based on Python"

  When it comes to iterators, we have to talk about the iterator protocol. The iterator protocol means: the object must provide a __next__() method, which either returns the next item in the iteration or throws a StopIteration exception (equivalent to reporting an error) meaning) to terminate the iteration. However, objects that follow this protocol are called iterable objects , also known as iterators. In Python, the object that a for loop operates on is an iterable object. It may cause some misunderstandings here, because we all know that for loops can directly traverse collections such as lists, tuples or strings, etc., but these data types do not have the __next__() method mentioned above, which means that these The data type does not follow the iterator protocol at all, which means that lists, tuples, strings, or dictionaries are not iterable objects, so how exactly does a for loop work?

  First, verify that neither of the lists or strings, etc. just said are iterables:

So the question is, why the for loop operates on iterable objects, but these data types are not iterable objects, so why can the for loop operate on them? Here's how the for loop works:

In fact, before the for loop processes the data, it will call the __iter__() method to convert the data into an iterable object , then call the __next__() method of the iterable object , and catch the StopIteration exception , which also implements the traversal After all data is finished, it will end, and this exception will not be thrown.

#Use the while loop to simulate the for loop 
num_list = [1,2,3,4 ]
 #Call the __iter__() method of the data first to generate an iterable object 
list_iterable = num_list. __iter__ ()
 #Check the type of the iterable object and return <class 'list_iterator'> List iterator 
print (type(list_iterable))
 #Call the __next__() method of the iterable object to implement traversal, and catch the StopIteration exception 
while True:
     try :
         print (list_iterable .__next__ ( ))   #Traverse the list All elements in --- 1 2 3 4 except StopIteration:
         break
    

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325074210&siteId=291194637