The working principle of for loop in Python is detailed
- 2021-12-05 06:26:31
- OfStack
For example:
Action on list
>>> for elem in [1,2,3]:
... print(elem)
...
1
2
3
Action on String
>>> for c in "abc":
... print(c)
...
a
b
c
Act on a dictionary
>>> for k in {"age":10, "name":"wang"}:
... print(k)
...
age
name
Some people may not ask why so many different types of objects are supported
for
Statement, what other types of objects can be used in the
for
What about the statement? Before answering this question, we must first understand
for
The execution principle behind the loop.
for
Loop is the process of iterating over a container. What is iteration? Iteration is to read elements from a container object one by one until there are no more elements in the container. So, which objects support iterative operations? Is any object ok? Try customizing 1 class first to see if it is OK:
>>> class MyRange:
... def __init__(self, num):
... self.num = num
...
>>> for i in MyRange(10):
... print(i)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'MyRange' object is not iterable
The error stack log tells us very clearly that MyRange is not an iterable object, so it cannot be used for iteration, so what kind of object is an iterable object (
iterable
)?
Iterable objects need to implement
__iter__
Method and returns 1 iterator. What is an iterator? The iterator only needs to implement the
__next__
Method. Now let's verify why the following list supports iteration:
>>> x = [1,2,3]
>>> its = x.__iter__() # x This means that the list is an iterable object
>>> its
<list_iterator object at 0x100f32198>
>>> its.__next__() # its With this method, explain its Is an iterator
1
>>> its.__next__()
2
>>> its.__next__()
3
>>> its.__next__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
From the experimental results, the list is an iterable object because it implements the
__iter__
Method and returns 1 iterator object (
list_iterator
), because it implements the
__next__
Method. We see it constantly calling
__next__
Method, in fact, iterates to get the elements in the container until no more elements in the container are thrown
StopIteration
Until it's abnormal.
Then
for
How do statements loop? Here, I'm afraid you guessed, its steps are:
TypeError
Exception, if yes, call
__iter__
Method that returns 1 iterator
Constantly calling the iterator's
__next__
Method, returning 1 value in the iterator in sequence at a time
At the end of the iteration, when there are no more elements, an exception is thrown
StopIteration
This exception
python
It will be handled by itself and will not be exposed to developers
The same is true for tuples, dictionaries, and strings. After understanding the execution principle of for, we can implement our own iterators to use in for loops.
Front
MyRange
The error is reported because it does not implement these two methods in the iterator protocol, and now it continues to improve:
class MyRange:
def __init__(self, num):
self.i = 0
self.num = num
def __iter__(self):
return self
def __next__(self):
if self.i < self.num:
i = self.i
self.i += 1
return i
else:
# This exception must be thrown when a certain condition is met, otherwise it will iterate indefinitely
raise StopIteration()
Because it implements
__next__
Method, so
MyRange
It is already an iterator, so
__iter__
What is returned is the object itself
self
. Now try it in the for loop:
for i in MyRange(3):
print(i)
# Output
0
1
2
Have you found that custom
MyRange
Functions and built-in functions
range
Very similar.
for
The essence of a loop is to constantly call the iterator
__next__
Method until there is a
StopIteration
Exception, so any iterable object can be used in the
for
In the loop.