Python generator and iterator, Python generator Generator

Source: Internet
Author: User

Python generator and iterator, Python generator Generator
1. Generator

By using the list generation method, we can directly create a list. However, due to memory restrictions, the list capacity must be limited. In addition, creating a list containing 1 million elements not only occupies a large storage space, but if we only access the first few elements, the space occupied by the vast majority of elements is wasted. Therefore, if the list element can be calculated based on a certain algorithm, can we continue to calculate the subsequent elements in the loop process? In this way, you do not have to create a complete list to save a lot of space. In Python, such a mechanism for looping and computing is called generator.

 

There are many ways to create a generator. The first method is very simple. You only need to change [] of a list to (), and a generator is created:

>>> L = [x*x for x in range(10)]>>> L[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]>>> g = (x*x for x in range(10))>>> g<generator object <genexpr> at 0x7fafe19d2410>

To print the elements of the generator one by one, you can use the next () function to obtain:

>>> next(g)0>>> next(g)1>>> next(g)4>>> next(g)9>>> next(g)16>>> next(g)25>>> next(g)36>>> next(g)49>>> next(g)64>>> next(g)81>>> next(g)Traceback (most recent call last):  File "<stdin>", line 1, in <module>StopIteration

Each time you call next (), the next element of g is calculated. If no more elements exist, an error is returned.

#!/usr/bin/env pythong = (x*x for x in range(10))for n in g:    print(n)====================================0149162536496481

So we usually use the for loop to iterate it.

The pora-cut sequence cannot be written in the list generation type, but the function can: The above function is just one step away from generato.

def fib(max):    n, a, b = 0, 0, 1    while n < max:        print(b)        a, b = b, a + b        n = n + 1    return 'done'

Note:

a, b = b, a + b

Equivalent:

T = (B, a + B) # t is a tuplea = t [0] B = t [1]

The above function is just one step away from generato. You only need to change print (B) to yield B.
def fib(max):    n, a, b = 0, 0, 1    while n < max:        yield b        a, b = b, a + b        n = n + 1    return 'done'


2. iterator

Objects that can directly act on the for loop are collectively referred to as iteration objects: Iterable.

You can use Isinstance () to determine whether an object is an Iterable object.

 

>>> from collections import Iterable>>> isinstance([],Iterable)True>>> isinstance({},Iterable)True>>> isinstance('abc',Iterable)True>>> isinstance(100,Iterable)False>>> 

 

Can be called by the next () function and return the next worthwhile object called Iterator: Iterator.

You can use isinstance () to determine whether an object is an Iterator object:

>>> from collections import Iterator>>> isinstance((x for x in range(10)),Iterator)True>>> isinstance([],Iterator)False>>> isinstance({},Iterator)False

 

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.