Python path----------iterator

Source: Internet
Author: User

There are several types of data that are used directly for a For loop:

1. Data type of collection class: List tuple dict set STR, etc.

2. Generator generator, including generator and generator function with yiled

These objects, which can be used directly for the for loop, are called iterative object iterable.

1 #Coding=utf-82 3  fromCollectionsImportiterable4 5 Print(Isinstance ({}, iterable))#True6 Print(Isinstance ([], iterable))#True7 Print(Isinstance ('iterable', iterable))#True8 Print(Isinstance ((), iterable))#True9 Print(Isinstance (iterable))#False

Iterator: An iterator (Iterator) that can be called by next () to continually return the next value.

1  fromCollectionsImportIterator2 3 Print(Isinstance ({}, Iterator))#False4 Print(Isinstance ([], Iterator))#False5 Print(Isinstance ('iterable', Iterator))#False6 Print(Isinstance ((), Iterator))#False7 Print(Isinstance (x forXinchRange (5)), Iterator))#True8 9 #as noted above, lists, dictionaries, strings, ganso, etc. are not iterators (Iterator)

Can an iterative object become an iterator? The pass-Multiple built-in method ITER () can achieve

1  fromCollectionsImportIterator2 3 Print(Isinstance (ITER ({}), Iterator))#True4 Print(Isinstance (ITER ([]), Iterator))#True5 Print(Isinstance (ITER ('iterable'), Iterator))#True6 Print(Isinstance (ITER (()), Iterator))#True7 Print(Isinstance (x forXinchRange (5)), Iterator))#True

Summary:

1 #the nature of the for loop of Python is that it is continuously implemented by invoking the next function, such as the following two-segment code2 3 #Code One4 5  forXinchRange (10):6     Print(x)7 8 #Code two9it = iter ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])Ten  whileTrue: One     Try: Ax =Next (IT) -         Print(x) -     exceptstopiteration: the          Break - #code one is equivalent to code two

Python path----------iterator

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.