Overview
Iterators are a way to access the elements of a collection. The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without backing back.
Deferred or lazy evaluation (lazy evaluation)
Iterators do not require that you prepare all the elements in advance for the entire iteration. The element is evaluated only when it is iterated to an element, and before or after that, the element may not exist or be destroyed. This feature makes it particularly useful for traversing large or infinite collections.
Can iterate over objects
Iterators provide a unified interface for accessing collections. An iterator can be used whenever an object that implements the __iter__ () or __getitem__ () method is accessed.
Sequence: string, list, tuple
Non-sequential: dictionary, file
Custom class: User-defined class implements the object of the __iter__ () or __getitem__ () method
Creating an Iterator Object
Use the built-in factory function iter (iterable) to get an iterator object:
Grammar:
Iterator, ITER (collection)
Iterator, ITER (Callable,sentinel)
Description
Get an iterator from an object.
In the first form, the argument must supply it own iterator, or be a sequence.
In the second form, the callable is called until it returns the Sentinel.
Examples show:
1 build iterators using the __iter__ () method built into the object2>>>L1 = [1,2,3,4,5,6]3>>>i1 = L1.__iter__()4>>>PrintI15<listiterator Object at 0x7fe4fd0ef550>6>>>I1.next ()718>>>I1.next ()92Ten>>>I1.next () One3
1 build iterators with built-in factory functions 2 >>> L1 = [1,2,3,4,5,6 3 >>> I2 = iter (L1) 4 > >> print I2 <listiterator object at 0x7fe4fd0ef610> >>> I2.next () 7 1 8 >>> I2.next () 9 2< Span style= "color: #008080;" >10 >>> I2.next () 11 3
Description
For loop can be used for any iterator object
When the For loop starts, it is transferred to the ITER () built-in function via an iterative protocol, allowing an iterator to be obtained from the iteration object that contains the required next () method.
Python iterator (Iterator)