Language: EN

iteradores-e-iterables-en-python

Iterators and Iterables in Python

An Iterable in Python is any object that has an Iterator, and therefore can be traversed sequentially.

Predefined iterables include lists, tuples, strings, and sets.

# Examples of iterables
lista = [1, 2, 3, 4, 5]
cadena = "Python"
tupla = (1, 2, 3)
conjunto = {1, 2, 3}

Although we can create our own iterables (as we will see below).

Using Iterables

An iterable is any object that can be traversed in a for loop. For example, here is how to use an iterable directly in a for loop.

# Example of using an iterable in a for loop
lista = [1, 2, 3, 4, 5]

for elemento in lista:
    print(elemento)

# Output: 1, 2, 3, 4, 5

Internally, when we use for to traverse an Iterable object, we are using its iterator to get the different elements.

What is an Iterator?

An Iterator is an element that points to an element, generally belonging to a collection.

Technically, an iterator is simply an object that implements the methods __iter__() and __next__().

  • The __iter__() method returns the iterator object itself
  • The __next__() method returns the next element in the sequence

When there are no more elements to return, __next__() raises a StopIteration exception.

Creating an Iterator

Let’s see how we can create a custom iterator in Python.

# Example of creating a custom iterator
class Contador:
    def __init__(self, inicio, fin):
        self.inicio = inicio
        self.fin = fin

    def __iter__(self):
        self.numero = self.inicio
        return self

    def __next__(self):
        if self.numero <= self.fin:
            resultado = self.numero
            self.numero += 1
            return resultado
        else:
            raise StopIteration

# Using the custom iterator
contador = Contador(1, 5)
iterador = iter(contador)

for numero in iterador:
    print(numero)

# Output: 1, 2, 3, 4, 5

Practical Examples