Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How for loops work in Python

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on "how the for loop works in Python". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how the for loop works in Python.

For example:

Act on list

> Print (elem)... 123

Act on a string

For c in "abc":. Print (c)... abc

Act on a dictionary

For k in {"age": 10, "name": "wang"}:... Print (k)... agename

One may ask 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? Iteration is to read elements one by one from a container object until there are no more elements in the container. So, which objects support iterative operations? Is any object all right? Try to customize a class at random and see if it works:

> class MyRange:... Def _ _ init__ (self, num):... Self.num = num... > > for i in MyRange (10):. Print (I)... Traceback (most recent call last): File "", line 1, in TypeError: 'MyRange' object is not iterable

The error stack log clearly tells us that MyRange is not an iterable object, so it cannot be used for iteration, so what kind of object can be called an iterable object (iterable)?

Iterable objects need to implement the _ _ iter__ method and return an iterator. What is an iterator? The iterator only needs to implement the _ _ next__ method. Now let's verify why the list supports iterations:

> x = [1pr 2p3] > its = x.iteriteriterator _ () # x has this method, indicating that the list is iterable object > > its > 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 ", line 1, in StopIteration

From the experimental results, 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, just iterating over and over to get the elements in the container until no more elements in the container throw a StopIteration exception.

So how do for statements loop? At this point, I'm afraid you've guessed it, and its steps are:

First determine whether the object is an iterable object, if not, report an error directly, throw a TypeError exception, and if so, call the _ _ iter__ method and return an iterator

Constantly call the _ _ next__ method of the iterator, returning a value in the iterator sequentially each time

At the end of the iteration, when there are no more elements, an exception StopIteration is thrown. The exception python will handle itself and will not be exposed to the developer.

The same is true for tuples, dictionaries, and strings. Once we understand how for works, we can implement our own iterators for use in for loops.

The previous MyRange error is because it does not implement these two methods in the iterator protocol, and now continue 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 condition is reached Otherwise, raise StopIteration () will iterate endlessly.

Because it implements the _ _ next__ method, MyRange itself is already an iterator, so _ _ iter__ returns the self of the object itself. Now try it in the for loop:

For i in MyRange (3): print (I) # output 0 1 2

Have you found 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 act in the for loop.

At this point, I believe you have a deeper understanding of "how the for loop works in Python". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report