Un iterador en Python es un objeto que se utiliza para iterar sobre objetos iterables como listas, tuplas, dictados y conjuntos. El objeto de iteradores de Python se inicializa utilizando el iterador() método. Utiliza el próximo() método de iteración.
- __iter__(): El método iter() se llama para la inicialización de un iterador. Esto devuelve un objeto iterador __next__(): El siguiente método devuelve el siguiente valor para el iterable. Cuando usamos un bucle for para atravesar cualquier objeto iterable, internamente usa el método iter() para obtener un objeto iterador, que además usa el método next() para iterar. Este método genera un StopIteration para señalar el final de la iteración.
Ejemplo de iteración de Python()
Python3
nat vs cama
string>=> 'GFG'> ch_iterator>=> iter>(string)> print>(>next>(ch_iterator))> print>(>next>(ch_iterator))> print>(>next>(ch_iterator))> |
>
>
Producción :
G F G>
Crear y recorrer un iterador usando iter() y next()
A continuación se muestra un iterador de Python simple que crea un tipo de iterador que itera desde 10 hasta un límite determinado. Por ejemplo, si el límite es 15, imprime 10 11 12 13 14 15. Y si el límite es 5, no imprime nada.
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)> |
>
>
Producción:
10 11 12 13 14 15>
Iterando sobre iterable incorporado usando el método iter()
En las siguientes iteraciones, el estado de iteración y la variable iteradora se administran internamente (no podemos verlo) usando un objeto iterador para atravesar el iterable incorporado como lista , tupla , dictar , etc.
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]))> |
>
>
Producción:
List Iteration geeks for geeks Tuple Iteration geeks for geeks String Iteration G e e k s Dictionary Iteration xyz 123 abc 345>
Iterable vs Iterador
El iterable de Python y el iterador de Python son diferentes. La principal diferencia entre ellos es que iterable en Python no puede guardar el estado de la iteración, mientras que en los iteradores se guarda el estado de la iteración actual.
Nota: Cada iterador también es un iterable, pero no todos los iterables son un iterador en Python.
Leer más – Diferencia entre iterable e iterador.
Iterando sobre un Iterable
Iterando sobre cada elemento del iterable.
Python3
booleano a cadena
tup>=> (>'a'>,>'b'>,>'c'>,>'d'>,>'e'>)> for> item>in> tup:> >print>(item)> |
>
>
Producción:
a b c d e>
Iterando en un iterador
Python3
cómo salir de un bucle while java
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))> |
>
>
Producción:
Inside loop: a b c Outside loop: d e>
Obteniendo el error StopIteration al usar el iterador
Iterable en Python se puede iterar varias veces, pero los iteradores generan un error StopIteration cuando todos los elementos ya están iterados.
Aquí, estamos intentando obtener el siguiente elemento del iterador después de completar el bucle for. Dado que el iterador ya está agotado, genera una excepción StopIteration. Mientras que, al usar un iterable, podemos iterar varias veces usando el bucle for o podemos obtener elementos usando la indexación.
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))> |
>
>
Producción:
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>