Python non-return _ iterator

Source: Internet
Author: User

Iterators:

The For loop can iterate over two types of data:

1. such as list, tuple, dict, set, etc.

2. Functions with the yield keyword or can be called with __next__ (), which is the generator

The objects that can be called by for are iterable, and you can use the Isinstance method to verify that they are iterable

 from   collections import Iterablea  =[< Span style= "COLOR: #800080" >1 ,  " b  Span style= "COLOR: #800000", ", "  c  Span style= "COLOR: #800000" > " ]b  ={  name   ":  '   

So since list, tuple, dict, set and so on are all iterable, is that iterator? We can still use isinstance to judge.

 from Import iteratorisinstance (a,iterator) isinstance (b,iterator)
Output Result:
False
False

It is obvious that list, set, tuple, and dict are not iterators, but they can be iterated. Can you turn them into iterators, too?

 from Import Iteratora=[1,'b','C']isinstance (ITER (a ), Iterator)
Output Result:
True
  

Summary: List, Set, tuple, dict, etc. are iterable, but not iterator, using the ITER () method can make an iterative object into an iterator.

Let's see if the generator is iterable and iterator, and we'll use isinstance to verify it.

From collections Import Iterator
def func1 (x): while x <: = x**2 yield n x+ =1F=func1 (200)
Isinstance (F,iterator) #判断是否是迭代器
Output Result:
True
 from Import iterableisinstance (f,iterable)
Output Result:
True

Summary: The generator is both iterable and iterator.

Summary: All that can be used for a loop is the iterable type.

List, dict, set, tuple, etc. are all iterable but not iterator, and can be changed to iterator by the ITER () function.

The generators are iterators.

   

Python non-return _ 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.