The difference between iterators and generators in Python

Source: Internet
Author: User

1 #!/usr/bin/python2 defPower (values):3      forValueinchvalues:4         Print "powing%s"%value5         yieldvalue6 defAdd (values):7      forValueinchvalues:8         ifValue% 2 = =0:9             yieldValue + 3Ten         Else: One             yieldValue + 2 Aelements = [1, 4, 7, 9, 12, 19] - Add (Power (elements)) -  forIinchAdd (Power (elements)): the         Print(i)

First look at the result of the above code:

Powing 1
3
Powing 4
7
Powing 7
9
Powing 9
11
Powing 12
15
powing 19
21st
Power is no longer a function, it is a generator, note that power does not execute print during the call, but when it is traversed with for, it executes print, so you first need to know that this is the difference between the generator and the function!! Many tutorials even the most basic functions and the difference between the generator is not mentioned!! The next step is to say the difference between a generator and an iterator:

1. In terms of grammar:

The generator is created with the yield statement in the function. The creation of iterators is first of all function-independent and can be created with ITER ([up]).

2. In terms of use:

Because the generator is created using a function, all the procedures inside the generator are executed, but note that the process inside the generator is executed only when it is called by the next () or for loop, as the above example simply calls the Add object. The process inside the add is not executed!

Iterators can also be called for and next but because there are no other procedures, only values are returned when called, and no other action

The difference between iterators and generators in Python

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.