Home Backend Development Python Tutorial Summary of some tips for implementing iterators in Python programming

Summary of some tips for implementing iterators in Python programming

Jul 21, 2016 pm 02:53 PM
python Iterator

yield implements iterator
As described in the introduction, it is a little troublesome to implement iter, next manually every time to implement an iterable function, and the required code is also relatively objective. In python, an iterator can also be implemented by using yield. Yield has a key function. It can interrupt the current execution logic, maintain the scene (the status of various values, the execution position, etc.), return the corresponding value, and the next execution can seamlessly continue the last time. Continue execution at the place where the loop continues until the pre-set exit conditions are met or an error occurs and is forced to be interrupted.
Its specific function is that it can be used as return to return a value from the function. The difference is that after returning with yield, the function can continue execution from the point returned by yield. In other words, yield returns the function, hands a return value to the caller, and then "teleports" back, allowing the function to continue running until the yield statement returns a new value. After using yield to return, what the caller actually gets is an iterator object, and the value of the iterator is the return value. Calling the next() method of the iterator will cause the function to restore the execution environment of the yield statement and continue running until Until the next yield is encountered, if no yield is encountered, an exception will be thrown to indicate the end of the iteration.
Take a look at an example:

>>> def test_yield():
... yield 1
... yield 2
... yield (1,2)
...
>>> a = test_yield()
>>> a.next()
1
>>> a.next()
2
>>> a.next()
(1, 2)
>>> a.next()
Traceback (most recent call last):
 File "<stdin>", line 1, in &#63;
StopIteration
Copy after login

Just listening to the description, I think it is very consistent with the way iterators work, right? Indeed, yield can turn the function it is located into an iterator. Let’s briefly describe the work using the most classic example of the Fibonacci sequence. Method:

def fab(max): 
 n, a, b = 0, 0, 1 
 while n < max:
 print b, "is generated" 
 yield b
 a, b = b, a + b 
 n = n + 1 

>>> for item in fab(5):
... print item
... 
1 is generated
1
1 is generated
1
2 is generated
2
3 is generated
3
5 is generated
5

Copy after login

Let’s recall the syntactic sugar of the for keyword. When traversing the Fibonacci sequence values ​​within 5, it is obvious that fab(5) generates an iterable object. When the traversal starts, its iter The method is called to return an actual working iterator object, and each call to its next method returns a Fibonacci sequence value which is then printed.
We can print out the properties of the object returned by calling the generator function to see what is going on:

>>> temp_gen = fab(5)
>>> dir(temp_gen)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'gi_code', 'gi_frame', 'gi_running', 'next', 'send', 'throw']
Copy after login

As described above, simply calling fab will not cause the function to start returning any value immediately, and it can be seen from the printed attribute list of fab(5) that the object returned by the generator function contains __iter__, next realization. Compared with our manual implementation, using yield is very convenient to achieve the functions we want, and the amount of code is reduced a lot.

Generator Expression
Another way to generate iterator objects more elegantly in python is to use generator expression. It has a very similar writing method to list parsing expression. It just changes the square brackets [] into () , but the actual effect of small changes is indeed very different:

>>> temp_gen = (x for x in range(5))
>>> temp_gen
<generator object <genexpr> at 0x7192d8>
>>> for item in temp_gen:
... print item
... 
0
1
2
3
4
>>> dir(temp_gen)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'gi_code', 'gi_frame', 'gi_running', 'next', 'send', 'throw']
Copy after login

After reading the description of yield above, this example and the corresponding output log are quite straightforward. Whether it is the print log description of temp_gen, the output result of the for statement traversal or the attribute list output by calling dir, they are all naked. Indicates that the generator expression does produce an object capable of supporting iteration. In addition, functions can also be called in expressions to add appropriate filtering conditions.

Built-in libraries itertools and iter
Python’s built-in library itertools provides a large number of tool methods that can help us create objects that can efficiently traverse and iterate. It contains many interesting and useful methods, such as chain, izip/izip_longest, combinations, ifilter and so on. There is also a built-in iter function in python that is very useful, it can return an iterator object, and then you can view the corresponding help document for a brief look:

>>> iter('abc')
<iterator object at 0x718590>
>>> str_iterator = iter('abc')
>>> next(str_iterator)
'a'
>>> next(str_iterator)
'b'
>>> lst_gen = iter([1,2,3,4])
>>> lst_gen
<listiterator object at 0x728e30>
>>> dir(lst_gen)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__length_hint__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'next']

>>> help(iter)
Help on built-in function iter in module builtins:

iter(...)
 iter(iterable) -> iterator
 iter(callable, sentinel) -> iterator

 Get an iterator from an object. In the first form, the argument must
 supply its own iterator, or be a sequence.
 In the second form, the callable is called until it returns the sentinel.

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

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.

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.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

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.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles