Difference between Iterator and Generator in Python

Source: Internet
Author: User
Keywords python generator iterator

Iterator:

It is a more abstract concept, any object, if its class has next method and iter method return to itself. For container objects such as string, list, dict, tuple, etc., it is convenient to use for loop traversal. In the background, the for statement 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. It accesses the elements in the container one by one in the container. Next() is also a built-in function of Python. When there are no subsequent elements, next() will throw a StopIteration exception


Generator:

It is a simple and powerful tool for creating iterators. They are written like regular functions, but use yield statements when you 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 the data values)


Difference: 

The generator can do everything the iterator 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 method of creating and saving program state, when the generator ends, it will automatically throw a StopIteration exception

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.