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

What is the difference between iterator and generator in python

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

Share

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

This article introduces what is the difference between iterators and generators in python. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

The difference between generators and iterators in python (the code is tested under Python3.5):

Iterator

Definition:

For container objects such as list, string, tuple, dict, and so on, it is convenient to use for loop traversal. In the background, the for statement calls the iter () function on the container object. Iter () is the python built-in function. The iter () function returns an iterator object that defines the next () method, which accesses the elements in the container one by one. Next () is also a python built-in function. When there are no subsequent elements, next () throws a StopIteration exception informing for that the statement loop ends.

The iterator is used to help us record the location accessed by each iteration, and when we use the next () function on the iterator, the iterator returns to us the data of the next location it records. In fact, when you use the next () function, you call the _ next_ method of the iterator object (the _ next_ method of the object in Python3 and the next () method of the object in Python2). So, if we want to construct an iterator, we have to implement its _ next_ method. But that's not enough. Python requires the iterator itself to be iterated, so we have to implement the _ iter_ method for the iterator, and the _ iter_ method returns an iterator, which itself is an iterator, so the iterator's _ iter_ method returns its own self.

Interpretation of some terms:

1, iterator protocol: the object needs to provide the next () method, which either returns the next item in the iteration or raises a StopIteration exception to terminate the iteration.

2, iterable object: the iterator protocol object is implemented. List, tuple, and dict are all Iterable (iterable objects), but not Iterator (iterator objects). But you can use the built-in function iter () to turn all of these into Iterable (iterator objects).

3The essence of the iter for item in Iterable loop is to first obtain the iterator of the iterated object Iterable through the next () function, and then call the next () method on the obtained iterator to get the next value and assign it to the loop. When an exception of StopIteration is encountered, the loop ends.

Python comes with a container object case:

# casually define a listlistArray= [1 listArray 2) 3] # use the iter () function iterName=iter (listArray) print (iterName) # the result is as follows: it is a list list iterator # print (next (iterName)) # does not iterate to the next element Throw an exception directly # deleted deleted Traceback (most recent call last): # File "Test07.py", line 32, in # StopIteration-

One class object in Python that implements the _ iter_ method and the _ next_ method is the iterator. The following example is a case of calculating the Fibonacci sequence.

Class Fib (object): def _ init__ (self, max): super (Fib, self). _ _ init__ () self.max = max def _ iter__ (self): self.a = 0 self.b = 1 return self def _ next__ (self): fib = self.an if fib > self.max: raise StopIteration self.a Self.b = self.b, self.a + self.b return fib# defines a main function Loop through each Fibonacci tangent def main (): number within # 20 fib = Fib (20) for i in fib: print (I) # Test if _ name__ = ='_ main__': main ()

Explanation:

In the implementation of this class, a _ iter_ (self) method is defined, which is called by iter () during the for loop and returns an iterator. Because when traversing, the python built-in function iter () is called directly, and iter () gets the object's iterator by calling _ iter_ (self). With an iterator, you can traverse the elements one by one. When traversing one by one, you also use the built-in next () function to traverse the iterator object by calling the object's _ next_ (self) method. So you need to implement both _ iter_ (self) and _ next_ (self) methods.

And because the _ next_ (self) method is implemented, when implementing _ iter_ (self), you can simply return self.

To sum up, it is:

When you loop through a custom container object, you use the python built-in function iter () to call the iterator object's _ iter_ (self) to get an iterator, and then loop through the iterator object's _ next_ (self) with next ().

Note: _ iter_ (self) will only be called once, while _ next_ (self) will be called n times until a StopIteration exception occurs.

Generator

Function:

> delay the operation. That is to say, the result is produced when it is needed, not immediately.

Note:

The generator can only be traversed once.

A generator is a special class of iterators

Classification:

The first category: generator functions: still use def to define functions, but use yield instead of return statements to return results. The yield statement returns one result at a time, and in the middle of each result, the state of the function is suspended so that execution continues next time from where it left.

The following examples are illustrated:

# Fibonaccine sequence def Fib (max): n, a, b = 0,0,1 while n < max: yield b a, b = b, a + b n = n + 1 return 'dear! There is no data.'# call the method and generate 10 numbers to f=Fib (10) # capture the value returned by the last return using a loop and save it in the value of the exception StopIteration while True: try: x=next (f) print ("f:", x) except StopIteration as e: print ("the last return value of the generator is:", e.value) break

The second category: generator expressions: similar to list derivation, except that a pair of curly braces [] is transformed into a pair of parentheses (). However, the generator expression produces a generator result object on demand, and you need to loop through it to get each element.

The following examples are illustrated:

# A list of xiaoke= [2 a for an in xiaoke 3 for i in gen 5] # generator generator, which is similar to list, but changes [] to () gen= (a for an in xiaoke) for i in gen: print (I) # the result is: why would 234 girls use a generator? Because of efficiency. # replacing list deduction with generator expressions can save both cpu and memory (RAM). # if you construct a list (list) just to pass it to another function, for example, to tuple () or set (), then replace it with a generator expression! # in this case, the list is directly transformed into a tuple kk=tuple (a for an in xiaoke) print (kk) # the result is: (2, 3, 4, 5) # some functions built into python, which can be recognized as generator expressions There is a pair of parentheses outside, that is, the generator result1=sum (a for an in range (3)) print (result1) # list derived result2=sum ([a for an in range (3)]) print (result2) about the difference between iterators and generators in python is shared here. I hope the above content can be helpful to you and learn more knowledge. If you think the article is good, you can share it for more people to see.

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

Internet Technology

Wechat

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

12
Report