Home  >  Article  >  Backend Development  >  The difference between python iterators and generators

The difference between python iterators and generators

(*-*)浩
(*-*)浩Original
2019-06-22 16:12:173142browse

Iterator is a more abstract concept. Any object, if its class has next method and iter method, returns itself. For container objects such as string, list, dict, tuple, etc., use For loop traversal is very convenient.

The difference between python iterators and generators

The for statement in the background calls the iter() function on the container object. iter() is a built-in function of python. iter() returns an iterator object that defines the next() method, which accesses the elements in the container one by one. next() is also a built-in function of Python. When there are no subsequent elements, next() will throw a StopIteration exception. (Recommended learning: Python video tutorial)

# 随便定义一个list
listArray=[1,2,3]
# 使用iter()函数
iterName=iter(listArray)
print(iterName)

Generator (Generator) is a simple and powerful tool for creating iterators. They are written like regular functions, except that they use yield statements when they need to return data. Each time next() is called, the generator returns the position where it left off (it remembers the position where the statement was last executed and all data values)

# 菲波那切数列
def Fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1
    return '亲!没有数据了...'
# 调用方法,生成出10个数来
f=Fib(10)
# 使用一个循环捕获最后return 返回的值,保存在异常StopIteration的value中
while  True:
    try:
        x=next(f)
        print("f:",x)
    except StopIteration as e:
        print("生成器最后的返回值是:",e.value)
        break

Difference:

Generators can do everything that iterators can do, and because the iter() and next() methods are automatically created, the generator is particularly concise, and the generator is also efficient, using generator expressions instead of lists Parsing can save memory at the same time. In addition to the automatic methods for creating and saving program state, a StopIteration exception is automatically thrown when the generator terminates.

For more Python related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of The difference between python iterators and generators. 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