Simplifying Nested For Loops with itertools.product in Python

Posted by Afsal on 12-Jan-2024

Hi Pythonistas!

Today we will learn a simple trick to make the code simpler and more readable. Working with nested for loops in Python can sometimes lead to code that is less readable and more complex. One elegant solution to simplify nested loops is to use the itertools.product function, which generates the Cartesian product of input iterables.

Let consider an example we have three type of shirts and 3 available colors if we need to print all the combination we use nested for loop

Code

shirts = ["shirt 1", "shirt 2", "shirt 3"]
colors = ["red", "blue", "green"]

for shirt in shirts:
    for color in colors:
        print(shirt, color)

Output

shirt 1 red

shirt 1 blue

shirt 1 green

shirt 2 red

shirt 2 blue

shirt 2 green

shirt 3 red

shirt 3 blue

shirt 3 green

The same thing can be done more pythonic using itertools.product

Code

for shirt, color in itertools.product(shirts, colors):
    print(shirt, color)

Output

shirt 1 red

shirt 1 blue

shirt 1 green

shirt 2 red

shirt 2 blue

shirt 2 green

shirt 3 red

shirt 3 blue

shirt 3 green

 We can see that the itertool.product makes the code cleaner. 

I hope you have learned something from this post. Please share your valuable suggestions with afsal@parseltongue.co.in