preamble
for... .in is the most used statement by Python programmers. for loops are used to iterate over elements in container objects, which can be lists, tuples, dictionaries, collections, files, or even custom classes or functions, for example:
Working with Lists
>>> for elem in [1,2,3]: ... print(elem) ... 1 2 3
act on a tuple
>>> for i in ("zhang", "san", 30): ... print(i) ... zhang san 30
Applies to strings
>>> for c in "abc": ... print(c) ... a b c
act on a set
>>> for i in {"a","b","c"}: ... print(i) ... b a c
Acting on Dictionaries
>>> for k in {"age":10, "name":"wang"}: ... print(k) ... age name
Acting on documents
>>> for line in open(""): ... print(line, end="") ... Fabric==1.12.0 Markdown==2.6.7
One might wonder why so many different types of objects support for statements, and what other types of objects can be used in for statements. Before we answer this question, we need to understand the execution principle behind the for loop.
A for loop is a process of iterating over a container. What is iteration? What is iteration? Iteration is the process of reading elements from a container object one by one until there are no more elements in the container. So, which objects support iteration? Can any object do it? Try a custom class and see if it works:
>>> class MyRange: ... def __init__(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 can't be used for iteration, so what exactly makes an object iterable?
Iterable objects need to implement the __iter__ method and return an iterator, what is an iterator? Iterators only need to implement the __next__ method. Now let's verify why lists support iteration:
>>> x = [1,2,3] >>> its = x.__iter__() # x has this method, indicating that the list is an iterable object >>> its <list_iterator object at 0x100f32198> >>> its.__next__() # its has this method, indicating that 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 test results, it appears that the list is an iterable object because it implements the __iter__ method and returns an iterator object (list_iterator) because it implements the __next__ method. We see that it keeps calling the __next__ method, which is actually iterating over the elements in the container until there are no more elements in the container to throw the StopIteration exception.
So how does the for statement loop? By this point, I'm afraid you've guessed that it steps:
- First determine whether the object is an iterable object, if not, report an error and throw a TypeError exception, if so, call the __iter__ method and return an iterator.
- Constantly call the iterator's __next__ method, returning one value from the iterator at a time in sequence
- At the end of the iteration, when there are no more elements, the exception StopIteration is thrown, which python handles itself and does not expose to the developer.
The same is true for tuples, dictionaries, and strings. Once you've figured out how for works, you can implement your own iterator for use in a for loop.
The previous MyRange reported an error because it didn't implement these two methods in the iterator protocol, so let's continue to improve it:
class MyRange: def __init__(self, num): = 0 = num def __iter__(self): return self def __next__(self): if < : i = += 1 return i else: # This exception must be thrown when a certain condition is reached, otherwise it will iterate indefinitely raise StopIteration()
Because it implements the __next__ method, MyRange itself is already an iterator, so __iter__ returns the object itself, self. now try it in a for loop:
for i in MyRange(3): print(i) # Output 0 1 2
Have you noticed that the custom MyRange function is very similar to the built-in function range? The essence of the for loop is to keep calling the iterator's __next__ method until there is a StopIteration exception, so any iterable object can be used in the for loop.
summarize
The above is the entire content of this article, I hope that the content of this article on your learning or work can bring some help, if there are questions you can leave a message to exchange, thank you for my support.