Python iterators and generators

Source: Internet
Author: User

Python iterators and generator iterators

An iterator is an object that implements an iterator protocol, and the iterator protocol in Python is that an object with the next method advances to the next result, and Stopiteration is thrown at the end of a series of results.

In the For loop, Python automatically calls the Factory function iter () to get the iterator, automatically calls next () to get the element, and completes the work of checking the stopiteration exception.

Several commonly used built-in data structures tuple, list, set, dict all support iterators, and strings can also use iterative operations.

You can also implement an iterator yourself, as described above, by simply returning an object in the class's __iter__ method, which has a next () method that throws the stopiteration exception at the appropriate time. But there are few times when you need to implement an iterator yourself, and even if you need it, it's easier to use the generator.

#!/usr/bin/env python#Coding=utf-8classTest:def __init__(self, input_list): Self.list=input_list self.i=0def __iter__(self):return SelfdefNext (self):ifSELF.I = =Len (self.list): self.i=0Raisestopiteration self.i+ = 1returnSELF.LIST[SELF.I-1]

One of the obvious benefits of using iterators is that you only read one piece of data from the object at a time, without causing too much memory overhead.

For example:

/ * Load the file into memory one at a time and print it on a line-by-row basis. When the file is large, the memory overhead of this method is very large * /For in open ("test.txt"). ReadLines ():     Print  Line / * This is the simplest and fastest to use, he does not explicitly read the file, but instead uses the iterator to read one line at a time * /  for  in open ("test.txt"):   #usefile iterators    Print Line
Generator

The generator is written in a similar way to the function definition, except that it is changed to yield in the return place.

There can be more than one yield in the generator. When the generator encounters a yield, it pauses to run the generator, returning the value after yield. When the generator is called again, it will continue to run from where it was just paused until the next yield.

The generator itself forms an iterator that uses the value returned by a yield at each iteration.

It is important to note that the return statement is not required in the generator, there is no need to specify a return value, and the default returns statement already exists in the generator

Builder expression

 for  in range (5))//Return iterator  <generator object <genexpr> at 0x7ff3e8f0d960>

列表解析,返回list

 for  in range (5)]//  return list1, 2, 3, 4]

Python iterators and generators

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.