Site icon Meccanismo Complesso

Python Lessons – 6.8 The itertools module

Python Lessons - 6.8 The itertools module
Python Lessons - 6.8 The itertools module

The itertools module

The itertools module is a module in the standard Python library that contains many functions that are very useful in functional programming, especially in iterations.

Let’s see an example

from itertools import count
for i in count(4):
    if i > 10:
        break
print(i) 

if you run it, you get:

>>>
4
5
6
7
8
9
10

Other Functions

There are other functions within the module that work similar to map () and filter ().

Let’s see an example

from itertools import accumulate, takewhile, chain
lista1 = list(accumulate(range(7)))
print(lista1)
lista2 = list(takewhile(lambda x: x<5, lista1))
print(lista2)
print(list(chain(lista1,lista2))) 

eseguendo

>>>
[0, 1, 3, 6, 10, 15, 21]
[0, 1, 3]
[0, 1, 3, 6, 10, 15, 21, 0, 1, 3]

Combinatorial functions

There are combinatorial functions in the itertools module as product() and permutation(). These functions are very useful when you want to get all the possible combinations of the elements.

from itertools import permutations, product
chars = ("A","B","C")
products = list(product(chars,chars))
combinations = list(permutations(lettere))
print(products)
print(combinations) 

if you run it, you get

>>>
[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'B'), ('C', 'C')]
[('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]

⇐ Go to Python Lesson 6.7 – Sets

Go to Python Lesson 7.1 – Classes⇒

Exit mobile version