Python のイテレータ

Python のイテレータは、リスト、タプル、辞書、セットなどの反復可能なオブジェクトを反復処理するために使用されるオブジェクトです。 Python イテレータ オブジェクトは、次のメソッドを使用して初期化されます。 iter() 方法。それは、 次() 反復のためのメソッド。

    __iter__(): iter() メソッドはイテレータの初期化のために呼び出されます。これは反復子オブジェクト __next__() を返します。 next メソッドは反復可能オブジェクトの次の値を返します。 for ループを使用して反復可能なオブジェクトを走査すると、内部的には iter() メソッドを使用して反復子オブジェクトを取得し、さらに next() メソッドを使用して反復処理を行います。このメソッドは、StopIteration を発生させて、反復の終了を通知します。

Python iter() の例

Python3




string> => 'GFG'> ch_iterator> => iter> (string)> print> (> next> (ch_iterator))> print> (> next> (ch_iterator))> print> (> next> (ch_iterator))>

出力:

G F G 

iter() と next() を使用したイテレータの作成とループ

以下は、10 から指定された制限まで反復するイテレータ型を作成する単純な Python イテレータです。たとえば、制限が 15 の場合、10 11 12 13 14 15 が出力されます。また、制限が 5 の場合は、何も出力されません。

Python3




# A simple Python program to demonstrate> # working of iterators using an example type> # that iterates from 10 to given value> # An iterable user defined type> class> Test:> > # Constructor> > def> __init__(> self> , limit):> > self> .limit> => limit> > # Creates iterator object> > # Called when iteration is initialized> > def> __iter__(> self> ):> > self> .x> => 10> > return> self> > # To move to next element. In Python 3,> > # we should replace next with __next__> > def> __next__(> self> ):> > # Store current value ofx> > x> => self> .x> > # Stop iteration if limit is reached> > if> x>>> self> .limit:> > raise> StopIteration> > # Else increment and return old value> > self> .x> => x> +> 1> ;> > return> x> # Prints numbers from 10 to 15> for> i> in> Test(> 15> ):> > print> (i)> # Prints nothing> for> i> in> Test(> 5> ):> > print> (i)>

出力:

10 11 12 13 14 15 

iter() メソッドを使用した組み込み反復可能オブジェクトの反復

次の反復では、反復状態と反復子変数は、次のような組み込み反復可能オブジェクトを横断する反復子オブジェクトを使用して内部で管理されます (目には見えません)。 リスト タプル 辞書 、など。

Python3




# Sample built-in iterators> # Iterating over a list> print> (> 'List Iteration'> )> l> => [> 'geeks'> ,> 'for'> ,> 'geeks'> ]> for> i> in> l:> > print> (i)> > # Iterating over a tuple (immutable)> print> (> ' Tuple Iteration'> )> t> => (> 'geeks'> ,> 'for'> ,> 'geeks'> )> for> i> in> t:> > print> (i)> > # Iterating over a String> print> (> ' String Iteration'> )> s> => 'Geeks'> for> i> in> s :> > print> (i)> > # Iterating over dictionary> print> (> ' Dictionary Iteration'> )> d> => dict> ()> d[> 'xyz'> ]> => 123> d[> 'abc'> ]> => 345> for> i> in> d :> > print> (> '%s %d'> %> (i, d[i]))>

出力:

List Iteration geeks for geeks Tuple Iteration geeks for geeks String Iteration G e e k s Dictionary Iteration xyz 123 abc 345 

イテラブルとイテレータ

Python イテラブルと Python イテレータは異なります。それらの主な違いは、Python の iterable では反復の状態を保存できないのに対し、イテレータでは現在の反復の状態が保存されることです。

注記: すべての反復子は反復可能でもありますが、Python ではすべての反復可能が反復子であるわけではありません。
続きを読む – iterable と iterator の違い。

Iterable での反復

反復可能オブジェクトの各項目を反復します。

Python3




tup> => (> 'a'> ,> 'b'> ,> 'c'> ,> 'd'> ,> 'e'> )> for> item> in> tup:> > print> (item)>

出力:

a b c d e 

イテレータでの反復

Python3




tup> => (> 'a'> ,> 'b'> ,> 'c'> ,> 'd'> ,> 'e'> )> # creating an iterator from the tuple> tup_iter> => iter> (tup)> print> (> 'Inside loop:'> )> # iterating on each item of the iterator object> for> index, item> in> enumerate> (tup_iter):> > print> (item)> > # break outside loop after iterating on 3 elements> > if> index> => => 2> :> > break> # we can print the remaining items to be iterated using next()> # thus, the state was saved> print> (> 'Outside loop:'> )> print> (> next> (tup_iter))> print> (> next> (tup_iter))>

出力:

Inside loop: a b c Outside loop: d e 

イテレータの使用中に StopIteration エラーが発生する

Python の Iterable は複数回反復できますが、すべての項目が既に反復されている場合、反復子は StopIteration エラーを発生させます。

ここでは、for ループの完了後にイテレータから次の要素を取得しようとしています。イテレータはすでに使い果たされているため、StopIteration 例外が発生します。一方、イテラブルを使用すると、for ループを使用して複数回反復処理したり、インデックスを使用して項目を取得したりできます。

Python3




iterable> => (> 1> ,> 2> ,> 3> ,> 4> )> iterator_obj> => iter> (iterable)> print> (> 'Iterable loop 1:'> )> # iterating on iterable> for> item> in> iterable:> > print> (item, end> => ','> )> print> (> ' Iterable Loop 2:'> )> for> item> in> iterable:> > print> (item, end> => ','> )> print> (> ' Iterating on an iterator:'> )> # iterating on an iterator object multiple times> for> item> in> iterator_obj:> > print> (item, end> => ','> )> print> (> ' Iterator: Outside loop'> )> # this line will raise StopIteration Exception> # since all items are iterated in the previous for-loop> print> (> next> (iterator_obj))>

出力:

Iterable loop 1: 1,2,3,4, Iterable Loop 2: 1,2,3,4, Iterating on an iterator: 1,2,3,4, Iterator: Outside loop Traceback (most recent call last): File 'scratch_1.py', line 21, in print(next(iterator_obj)) StopIteration