current position:Home>Iterator of Python basic language

Iterator of Python basic language

2022-01-30 06:53:48 Alvin305

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities



Iteration is a way to access collection elements . An iterator is an object that remembers the traversal position . The iterator object is accessed from the first element of the collection , Until all elements are accessed . Iterators can only go forward, not backward .

1. Iteratable object

python Some data types in the language can be used directly for Loop to get the element value , such as :

Collection data type :list,tuple,dict,set,str etc.

generator (generator), Including generator and belt yield Of generator function

These can act directly on for Circular objects are collectively called iteratable objects :Iterable

2. Decide if you can iterate

You can use isinstance() Function to determine whether an object is an iteratable object Iterable

>>> from collections import Iterable

>>> isinstance([],Iterable)
>>> True

>>> isinstance({},Iterable)
>>> True

>>> isinstance("abc",Iterable)
>>> True

>>> isinstance((x for x in range(10)),Iterable)
>>> True

>>> isinstance(100,Iterable)
>>> False
 Copy code 

We know that generators can not only use for Loop through to get the element , You can also use next() The function keeps calling to return the next value , Until the last throw StopIteration An error means that the next value cannot be returned .

3. iterator

Can be next() The object that function calls and returns the next value continuously is called an iterator :Iterator.

use isinstance() Function to determine whether an object is an iterator object :

>>> from collections import Iterator

>>> isinstance([],Iterator)
>>> False

>>> isinstance({},Iterator)
>>> False

>>> isinstance('abc',Iterator)
>>> False

>>> isinstance((x for x in range(10)),Iterator)
>>> True

>>> isinstance(100,Iterator)
>>> False
 Copy code 

From the above code, you can see the list , aggregate , Dictionaries , Although strings are iteratable objects, they are not iterators . The generator is both an iteratable object and an iterator .

4. iter() function

It says that all generators are Iterator. and list,dict,str Such iteratable objects are not Iterator, But we can pass iter() The function converts it to Iterator. as follows :

>>> isinstance(iter([]),Iterator)
>>> True

>>> isinstance(iter({}),Iterator)
>>> True

>>> isinstance(iter('abc'),Iterator)
>>> True
 Copy code 


  • What works for The objects of the loop are all Iterable type
  • Usually used as next() Function objects are Iterator type
  • The collection data type is as follows list,dict,str Wait, although it is Iterable No Iterator, But through iter() Function to Iterator

copyright notice
author[Alvin305],Please bring the original link to reprint, thank you.

Random recommended