The internal implementation principle of for...in... in python

The for loop traversal is actually to take out the iterator in the iterable object and then operate the next() operation on the iterator continuously, and then deal with the exception thrown when the iterator is next() for the last time.

Below we use a while to simulate the implementation of for...in...

lists = [i * 2 for i in range(5)]
for temp in lists:
    print(temp, end='')

print('\r\nThe following is the output of using while to simulate for...in...')

iterator_ = iter(lists)
while True:
    try:
        print(next(iterator_), end='')
    except StopIteration as ret:
        # print (ret)
        break

The output is

02468
Below is the output of simulating for...in... using while
02468



Guess you like

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