"Python" iterates over objects, iterators, generators

Source: Internet
Author: User
Tags iterable

Object iterable can be iterated

An object that can act directly on a for loop is called an iterative object.

There are data types such as list, dict, tuple, set, str, and generator (including generators and generator function with yield). Includes ordered and unordered objects.

To determine whether an object is a Iterable object. Here's how:

From collections Import iterable

Isinstance ([],iterable)

Iterator iterator

Iterations, that is, something to repeat several times, as you do in the loop.

Whether an object can be iterated depends on whether the object has a __iter__ method, as long as the object implements the __iter__ method, invokes the __iter__ method of the object, returns an iterator that must have the next method (no parameters are required to invoke the method), When the next method of the iterator is called, the iterator returns its next value, and when no value in the iterator can be returned, it throws an exception named Stopiteration, stopping the iteration.

To be exact, an object that implements the __iter__ method is iterative, and an object that implements the next method is an iterator.

For example, the file has both the ITER method and the next method, is an iterative object is also an iterator, why also the ITER method. The ITER method generates a uniform iterator format for all the iterated objects.

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

1. Modify the state for the next call to the next () method

2. Generate return results for current call

Characteristics: Irreversible, can only move forward, can not retreat. You can only get the next data through the next () function, generate a value return when needed, and wait for the next call when it is not called.

The For loop works like this, and the For loop loops through an object, invokes the object's __iter__ method, gets the iterator, and then calls the next method of the iterator to get each value contained in the iterator.

To determine whether an object is a iterator object. Here's how:

From collections Import Iterator

Isinstance ((x for X in range (9)), Iterator)

The difference between an iterator and a list

Iterators are lazy, one after the other to get the value, can only be taken back. However, the length of the iterator cannot be obtained.

List to get all the values at once. If there are many values, the list consumes too much memory.

Cases:

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. (iterators defined with normal function syntax)

Two forms of expression for the generator:

Function Builder: Each time a result is returned using the yield keyword, multiple yields can appear in a function. Each yield in the function will return a result. After each yield is executed, the function becomes a pending (paused) state, and the next time it is called, it continues down from where it was last suspended.

Builder expression: A method similar to a list derivation is used, but the returned result is no longer a list, but a generator.

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

Can be used for a for loop, or it can be repeatedly called by the next () function and return the next value, only to the last throw Stopiteration error indicates that the next value cannot continue to be returned.

Summarize:

The objects that are available for the For loop are iterable types,

The objects that are available for the next () function are iterator types,

Generators are iterator objects, but list, dict, str and so on are iterable, but not iterator.

You can use the ITER () function to turn the list and other iterable into iterator.

"Python" iterates over objects, iterators, generators

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.