Python_ Difference between generator and iterator

Time:2021-12-3

What is the difference between iterators and generators? This question is often tortured as a soul during the interview. Today, let’s comb through the concept to the code as a summary and record.

The difference is:

  • The benefit of the generator is to delay the calculation and return one result at a time. In other words, it will not generate all results at once, which will be very useful for large data processing.

Basic concepts

  1. Iteration: when the created objects can be read one by one, it is called iteration.
    Lists, tuples, dictionaries, and strings are all iteratable objects. Numbers and Boolean values are non iterative objects.
  2. Iterator protocol: the object needs to provide the next () method to return the next item in the iteration until the stopiteration exception is thrown.
  3. Iteratable object: implements the iterator protocol object. List, tuple and dict are iteratable objects, but not iterators.
    You need to use the built-in function ITER () to turn these into iteratable objects.
  4. For item in iteratable: the essence of the loop is to first obtain the iterator of the iteratable object through the iter() function, and then continuously call the next() method on the obtained iterator,
    To get the next value and assign it to item. When the stopiteration exception is encountered, the loop ends.

Operate it

  • Iterator: an implementation in Python_ iter_ Methods and_ next_ Method is the iterator.
>>> list = [1,2,3]
>>> lt = iter(list)
>>> print(next(lt))
1
>>> print(next(lt))
2
>>> print(next(lt))
3
>>> print(next(lt))
Traceback (most recent call last):
  File "", line 1, in 
StopIteration
  • Generator: in essence, it dynamically generates iterative values and discards them directly after use, which can effectively save memory space, but these values can only be iterated once.
>>> def g():
...     for i in range(3):
...         yield i
... 
>>> g = g()
>>> next(g)
0
>>> next(g)
1
>>> next(g)
2
>>> next(g)
Traceback (most recent call last):
  File "", line 1, in 
StopIteration

The yield statement, like the return statement, functions as a return. However, yield is different from return. If you execute a return statement, you will directly return the value of the expression after return. However, when the yield statement is executed, a generator object is returned, and the current value of the generator object is the value of the expression following the yield statement. After the yield statement is called, the current function returns an iterator and the function pauses until the next iteration of the function.

The generator is an inert sequence. If we need to create a sequence of 0 ~ XXXXXXXX, such a large sequence will occupy memory. The generator will solve this problem.

Reference link:
http://dwz.date/daG5
http://dwz.date/daG6