Home Backend Development Python Tutorial Detailed explanation of how the for loop works in Python

Detailed explanation of how the for loop works in Python

Jul 02, 2017 am 10:45 AM
python how Work

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
Copy after login

Applies to tuples


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

Applies to string


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

Action on collection


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

Action In dictionary


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

Apply to file

##

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

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
Copy after login

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
Copy after login

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()
Copy after login

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
Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles