How to Flatten Nested Python For Loops

How to Flatten Nested Python For Loops

Python Tip: Use product from itertools to flatten your nested for loops.

Here is an example 👇

devices = ["192.168.1.1", "192.168.1.2", "192.168.1.3"]
interfaces = ["Gi0/1", "Gi0/2", "Gi0/3"]

# -- Using nested loops --
for d in devices:
    for i in interfaces:
        print(d, i)

# ... instead use itertools.product():

# -- Using itertools --
from itertools import product

for d, i in product(devices, interfaces):
    print(d, i)
# Output:
# 192.168.1.1 Gi0/1
# 192.168.1.1 Gi0/2
# 192.168.1.1 Gi0/3
# 192.168.1.2 Gi0/1
# 192.168.1.2 Gi0/2
# 192.168.1.2 Gi0/3

Subscribe to our newsletter to keep updated.

Don't miss anything. Get all the latest posts delivered straight to your inbox.
Great! Check your inbox and click the link to confirm your subscription.
Error! Please enter a valid email address!