An example of the next function for the Python 3.2 iterator

  • 2020-12-19 21:07:30
  • OfStack

In python, an iterator of the ordered aggregate type can be obtained by using the iter function. Personally, I understand an iterator as a one-way linked list with an next pointer. The obtained iterator is the header of the linked list with an empty header, and the next pointer points to the first element of the ordered aggregate type. When accessing the next pointer to the last element of the linked list, python will report an error StopIteration.

If you use the next function with versions above Python3, note that the next() function with versions above 3.x changes to ___ ().

The code to print the contents of the file using the for iterator is as follows:


file_obj=open(r'E:\Project\Python\123.txt','r')
 
for string in file_obj:
 string=string.rstrip('\n')
 print(string)
 
file_obj.close()

In the above code, the file object file_obj is of the ordered aggregate type, and the for loop automatically calls the iterator of file_obj and calls the iterator's next function until an StopIteration error occurs.

The code below simulates an iterator in the for loop, explicitly calling the next function to access the elements of the string.


s='www.scu.edu.com'
 
it=iter(s)
length=len(s)
i=0
while i<length:
 print(it.__next__())
 i=i+1

Related articles: