Python -- 4, iteratable object, iterator, generator, python -- 4 Generator

Source: Internet
Author: User

Python -- 4, iteratable object, iterator, generator, python -- 4 Generator

Iterable

Objects that can directly act on the for loop are collectively called iteration objects.

Data types include list, dict, tuple, set, str, and generator (including generators and generator functions with yield ). Including ordered and unordered objects.

Determine whether an object is an iterable object. The method is as follows:

from collections import Iterable

isinstance([],Iterable)

 

Iterator

Iteration, that is, some things need to be repeated many times, just as they are done in a loop.

Whether an object can be iterated depends on whether the object has the _ iter _ method. If the object implements the _ iter _ method, when the _ iter _ method of the object is called, an iterator is returned, which must have the next method (no parameters are required when this method is called ), when the next method of the iterator is called, The iterator returns its next value. When no value in the iterator can be returned, it throws an exception named StopIteration, stop iteration.

To be accurate, an object that implements the _ iter _ method can be iterated, and an object that implements the next method is the iterator.

For example, the file has both the iter method and the next method, and the iteratable object and the iterator. Why the iter method. The iter method must generate a uniform iterator format for all iteratable objects.

Each time you call the next () method, two things are performed:

1. modify the status of the next call to the next () method

2. Generate returned results for the current CALL

Feature: Irreversible, only forward, not backward. You can only use the next () function to obtain the next data continuously. Values are generated and returned only when needed. If not called, the data is in sleep state and waits for the next call.

The for loop works like this. When a for loop loops an object, it calls the _ iter _ method of this object to obtain the iterator, then, call the next method of the iterator to obtain each value contained in the iterator.

Determine whether an object is an iterator object. The method is as follows:

from collections import Iterator

isinstance((x for x in range(9)),Iterator)

Differences between iterator and list

The iterator is inert. values obtained one after another can only be values later. However, the length of the iterator cannot be obtained.

List to obtain all values at a time. If there are many values, the list will occupy too much memory.

Example:

class test_class:

    def __init__(self,start_num,stop_num):

        self.start_num = start_num

        self.stop_num = stop_num

    def next(self):

        if self.start_num <  self.stop_num:

            self.start_num += 1

        return self.start_num

    def __iter__(self):

        return self

test_obj = test_class(0,3)

print test_obj.next()

>>>1

print test_obj.next()

>>>2

print test_obj.next()

>>>3

 

 

Generator

A special iterator. (Iterator defined by common function syntax)

Two expressions of the generator:

Function Generator: Use the yield keyword to return a result each time. Multiple yield values can appear in a function. Each yield in the function returns a result. Every time a yield is executed, the function changes to "suspended" (paused) state. The next time you call it again, the function continues to run down from the last suspended position.

Generator expression: a list-like derivation method is used, but the returned result is no longer a list, but a generator.

Example: (I for I in range (5 ))

It can be applied to the for loop, or can be continuously called by the next () function and return the next value. If the stopiteration error is thrown at the end, the next value cannot be returned.

 

Summary:

Objects that can be used for a for loop are of the iterable type,

Objects that can be used for the next () function are of the iterator type,

 

Generators are all iterator objects, but list, dict, str, etc. are iterable but not iterator.

You can use the iter () function to convert iterable such as list into iterator.

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.