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
list = [1, 2, 3, 4, 5]
string = "Python"
tuple = (1, 2, 3)
set = {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, it shows how to use an iterable directly in a for loop.

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

for element in list:
    print(element)

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

Internally, when we use for to traverse an Iterable object, it is internally using its iterator to obtain the different elements.

What is an Iterator?

An Iterator is an element that points to an element, usually from a collection.

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

  • 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 Counter:
    def __init__(self, start, end):
        self.start = start
        self.end = end

    def __iter__(self):
        self.number = self.start
        return self

    def __next__(self):
        if self.number <= self.end:
            result = self.number
            self.number += 1
            return result
        else:
            raise StopIteration

# Using the custom iterator
counter = Counter(1, 5)
iterator = iter(counter)

for number in iterator:
    print(number)

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

Advanced Examples

Creating an Iterator from an Iterable

Here it shows how to create an iterator from an iterable using the iter() function. Then, it uses calls to next() to obtain the elements of the iterator one by one.

list = [1, 2, 3, 4, 5]

# Create an iterator from an iterable
iterator = iter(list)

print(next(iterator))  # Output: 1
print(next(iterator))  # Output: 2
print(next(iterator))  # Output: 3
print(next(iterator))  # Output: 4
print(next(iterator))  # Output: 5
print(next(iterator))  # 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 traverse(iterable):
    iterator = iter(iterable)
    while True:
        try:
            element = next(iterator)
            print(element)
        except StopIteration:
            break

# Example of usage
string = "Python"
traverse(string)

# Output: P, y, t, h, o, n
  • The traverse function takes an iterable
  • Uses a while loop along with next() to print each element
  • Stops when it encounters a StopIteration exception