Talking about python iterator and python Generator

Source: Internet
Author: User

Talking about python iterator and python Generator

1. yield: Convert the function into a generator (generator)

Example: Fibonacci Series

def fib(num):  a, b, c = 1, 0, 1      while a <= num:    yield c    b, c = c, b + c    a += 1for n in fib(10):  print(n, end=' ')# 1 1 2 3 5 8 13 21 34 55

2. Iterable

All objects that can use the for loop, collectively referred to as Iterable)

from collections import Iterable, Iteratorprint(isinstance(fib(10), Iterable))print(isinstance(range(10), Iterable))# True# True

3. Iterator

You can use the next () <__ next _ ()> function to call an object that continuously returns the next value to become an Iterator (Iterator), indicating a sequence of inert computing.

List, dict, str is Iterable, not Iterator:

from collections import Iteratorprint(isinstance(list(), Iterator))# False

However, you can use the iter () function to change it to Iterator:

print(isinstance(iter(list()), Iterator))# True

Summary

The above is all about the python iterator in this article. I hope it will help you. Interested friends can continue to refer to this site: python fun project-sharing of pornographic image recognition code, Python implementing a simple verification code program, Python algorithm output 1-9 arrays to form a result of 100 of all computational formulas, etc, if you have any questions, you can leave a message at any time. The editor will reply to you in a timely manner. Thank you for your support!

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.