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
Creating an Iterator from an Iterable
Here is how to create an iterator from an iterable using the iter() function. Then, next() calls are used to get the elements from the iterator one by one.
lista = [1, 2, 3, 4, 5]
# Create an iterator from an iterable
iterador = iter(lista)
print(next(iterador)) # Output: 1
print(next(iterador)) # Output: 2
print(next(iterador)) # Output: 3
print(next(iterador)) # Output: 4
print(next(iterador)) # Output: 5
print(next(iterador)) # Stop iteration
In simplified form, this is what a for
loop does internally.
Using Iterators in Functions and Methods
This example shows how to use iterators within a function. In this case, it prints each element of an iterable.
# Using iterators in functions and methods
def recorrer(iterable):
iterator = iter(iterable)
while True:
try:
elemento = next(iterator)
print(elemento)
except StopIteration:
break
# Example of usage
cadena = "Python"
recorrer(cadena)
# Output: p, y, t, h, o, n
- The
recorrer
function takes an iterable - It uses a
while
loop along withnext()
to print each element - It stops when it encounters a
StopIteration
exception