Iteration in Python

Introduction

Iteration in programming in the broad sense is the organisation of data processing in which actions are repeated many times without calling themselves (unlike recursion).

In the narrow sense it is one step of an iterative, cyclic process.

When some action has to be repeated a large number of times, programming uses loops.

For example, you need to print the text "Hello, World!" 200 times.

Instead of repeating the same print command two hundred times one usually creates a loop , which repeats 200 times and 200 times does what is written in the loop body.

Iteration Protocols

Iteration Protocols
iterable iterator
An iterable is an object that can be turned into an iterator An iterator is an object over which iteration is possible
It can be passed to iter() to create an iterator It can be passed to next() to get the next value in the sequence

Iterators and iterables

An iterable is an object from which an iterator can be made by applying the function iter().

An iterator is an object that can be passed to the function next() to get the next element of the sequence

iter(iterable) → iterator

next(iterator)

Example

A good example of an iterable is a list . Let us try to get its elements one by one.

iterable = ['Benalmadena', 'Cordoba', 'Fuengirola', 'Malaga'] print(type(iterable)) print(next(iterable))

python iterable_ex.py

<class 'list'> Traceback (most recent call last): File "/home/andrei/iterable_ex.py", line 2, in <module> print(next(iterable)) TypeError: 'list' object is not an iterator

As you can see, the list class does not let you iterate over its elements directly.

Let us use the iter() function

iterable = ['Benalmadena', 'Cordoba', 'Fuengirola', 'Malaga'] iterator = iter(iterable) print(next(iterator)) print(next(iterator)) print(next(iterator)) print(next(iterator)) print(next(iterator))

python iterable_ex.py

Benalmadena Cordoba Fuengirola Malaga Traceback (most recent call last): File "/home/andrei/iterable_ex.py", line 7, in <module> print(next(iterator)) StopIteration

After applying iter() we could iterate over the list until its elements ran out.

def city(iterable): iterator = iter(iterable) try: return next(iterator) except StopIteration: raise ValueError("iterable is empty") # List print(city(["Benalmadena", "Cordoba", "Fuengirola", "Malaga"])) print(city(["Benalmadena", "Cordoba", "Fuengirola", "Malaga"])) # Set print(city({"Benalmadena", "Cordoba", "Fuengirola", "Malaga"})) print(city({"Benalmadena", "Cordoba", "Fuengirola", "Malaga"}))

python iterable_ex.py

Benalmadena Benalmadena Fuengirola Fuengirola

A set does not guarantee order, so instead of Fuengirola there may be any city.

StopIteration

Let us go through the whole iterator and handle the exception StopIteration

cities = ['Benalmadena', 'Cordoba', 'Fuengirola', 'Malaga'] g = iter(cities) while True: try: print(next(g)) except StopIteration: raise ValueError("iterable is empty") finally: print("Printing!") print("Great Success!") # will not be printed

python iterable_ex2.py

Benalmadena Printing! Cordoba Printing! Fuengirola Printing! Malaga Printing! Printing! Traceback (most recent call last): File "/home/andrei/iterable_ex2.py", line 21, in <module> print(next(g)) StopIteration During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/andrei/iterable_ex2.py", line 23, in <module> raise ValueError("iterable is empty") ValueError: iterable is empty

Article author: Andrei Olegovich