The internal mechanism of Python-for loop

In Python, the for loop can be used to iterate the elements in the container object, where the container object includes a list (list), a tuple (tuple), a dictionary (dict), a set (set), etc. But why can these objects be manipulated using a for loop?

First, define a simple class to try:

classTestRange:
 def __init__(self, num):
 self.num = num
for i inTestRange(10):print(i)

# Output
Traceback(most recent call last):
 File "<stdin ", line 1,in<module 
TypeError:'TestRange' object is not iterable

The error message indicates that the'TestRange' object is not an iterable object. So, what is an iterable object?

In an iterable object, a magic method of __iter__ needs to be implemented, and the return value of this method needs to be an iterator. So, what is an iterator?

Iterators only need to implement the __next__ magic method.

Take list as an example:

 nums =[13,12,33]
 iter_ret = nums.__iter__() #x has this method, indicating that the list is iterable, and the method returns an iterator
 iter_ret
< list_iterator object at 0x100f32198 

 iter_ret.__next__()13
 iter_ret.__next__()12
 iter_ret.__next__()33
 iter_ret.__next__()Traceback(most recent call last):
 File "<stdin ", line 1,in<module 
StopIteration

analysis:

As shown above, the __iter__ method is implemented in the list nums, and an iterator is returned, and the __next__ method is implemented in the iterator. In the process of calling __next__, it is returning the elements in nums until the error of StopIteration occurs.

In fact, the function of the for statement is similar. The internal mechanism of the for statement is:

The previous TestRange reported an error because it did not implement the two methods in the iterator protocol. Now continue to improve:

classTestRange:
 def __init__(self, _max):
 self.i =0
 self._max = _max

 def __iter__(self):return self

 def __next__(self):if self.i < self._max:
  i = self.i
  self.i +=1return i
 else:
  # When the stop condition is reached, this exception is thrown
  raise StopIteration()

# carry out testing
for i inTestRange(3):print(i)
# Output
 012

analysis:

Because this class has already implemented the __next__ method, the object created based on this class is itself an iterator. And because the iterable object needs to have the __iter__ method and return an iterator, so __iter__ returns the object itself self.

to sum up

So far this article on the internal mechanism of the Python-for loop is introduced. For more related python for loop content, please search for the previous articles of ZaLou.Cn or continue to browse the related articles below. Hope you will support ZaLou.Cn more in the future. !

Recommended Posts

The internal mechanism of Python-for loop
Consolidate the foundation of Python(7)
Consolidate the foundation of Python(6)
&quot;Consolidating the Foundation of Python&quot; (1)
Consolidate the foundation of Python (3)