10 Python Itertools To Make Your Code Neater, Cleaner, and Better

Implement the same thing with shorter code

Yang Zhou
TechToFreedom

--

Python Itertools Tricks To Make Your Code Neater
Image from Wallhaven

The beauty of Python lies in its simplicity.

Not only because Python’s syntax is elegant, but also due to it has many well-designed built-in modules that help us implement common functionalities efficiently.

The itertools module, which is a good example, provides many powerful tools for us to manipulate Python iterables in shorter code.

Do more by less. This is what you can get from the itertools module. Let’s check it out from this article.

1. itertools.product(): A Tricky Way To Avoid Nested Loops

When a program becomes more and more complicated, you may need to write nested loops. At the same time, your Python code will become ugly and unreadable:

list_a = [1, 2020, 70]
list_b = [2, 4, 7, 2000]
list_c = [3, 70, 7]

for a in list_a:
for b in list_b:
for c in list_c:
if a + b + c == 2077:
print(a, b, c)
# 70 2000 7

How to make the above code Pythonic again?

The itertools.product() function is your friend:

from itertools import product

list_a = [1, 2020, 70]…

--

--