search
HomeBackend DevelopmentPython TutorialDetailed explanation of how the for loop works in Python

If you are not very clear about the for loop in Python, then I suggest you read this article. This article mainly introduces you to the relevant information about how the for loop in Python works. It is very detailed and has certain reference and learning value for everyone. Friends who need it can take a look below.

Preface

for...in is the most commonly used statement by Python programmers. The for loop is used to iterate the containerObject# Elements in ##, these objects can be lists, tuples, dictionaries, collections, files, or even custom classes or functions, for example:

acts on lists


>>> for elem in [1,2,3]:
...  print(elem)
...
1
2
3

Applies to tuples


>>> for i in ("zhang", "san", 30):
...  print(i)
...
zhang
san
30

Applies to string


>>> for c in "abc":
...  print(c)
...
a
b
c

Action on collection


>>> for i in {"a","b","c"}:
...  print(i)
...
b
a
c

Action In dictionary


>>> for k in {"age":10, "name":"wang"}:
...  print(k)
...
age
name

Apply to file

##

>>> for line in open("requirement.txt"):
...  print(line, end="")
...
Fabric==1.12.0
Markdown==2.6.7

Some people may not know You have to ask, why do so many different types of objects support the for statement? What other types of objects can be used in the for statement? Before answering this question, we must first understand the execution principle behind the for loop.

The for loop is the process of iterating the 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? Can any object be used? Try customizing a class first 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 "<stdin>", line 1, in <module>
TypeError: &#39;MyRange&#39; object is not iterable

The error stack log tells us very clearly that MyRange is not an iterable object, so it cannot be used 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? Iterators only need to implement the next method. Now let's verify why the list supports iteration:

>>> x = [1,2,3]
>>> its = x.iter() # x有此方法,说明列表是可迭代对象
>>> its
<list_iterator object at 0x100f32198>

>>> its.next() # its有此方法,说明its是迭代器
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, 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 continuously calls the next method, which actually continuously iterates to obtain the elements in the container until there are no more elements in the container and a StopIteration exception is thrown.

So how does the for statement loop? At this point, I am afraid you have guessed it. The steps are:

    # First determine whether the object is an iterable object. If not, an error will be reported directly and a TypeError exception will be thrown. If so, , call the iter method and return an iterator
  • Continuously call the next method of the iterator, each time returning a value in the iterator in order
  • At the end of the iteration, if there are no more elements,
  • throw an exception

    StopIteration. Python will handle this exception by itself and will not expose it to developers

The same is true for tuples, dictionaries, and strings. After understanding the execution principle of for, 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. 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:
   # 达到某个条件时必须抛出此异常,否则会无止境地迭代下去
   raise StopIteration()

Because it implements next method, so MyRange itself is already an iterator, so iter returns the object itself. Now try using it in a for loop:

for i in MyRange(3):
 print(i)
# 输出
 0
 1
 2

Have you noticed that the custom MyRange function is very similar to the built-in function range. The essence of a for loop is to continuously call the next method of the iterator until a StopIteration exception occurs, so any iterable object can be used in a for loop.

The above is the detailed content of Detailed explanation of how the for loop works in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function