DEV Community

Discussion on: 5 Python Tricks in one line. Beginner vs Professional

Collapse
 
xtofl profile image
xtofl

If you replace the nested for loops (plain or in a generator expression) with a call to itertools.product, the reader will immediately see the intent.

result = product(first, second)
Enter fullscreen mode Exit fullscreen mode

Most of the times, this carthesian product is only iterated over and above example will do. If it needs to be stored, you'll need a tuple:

result  = [tuple(*p) for p in
    product(first, second, third)
]
Enter fullscreen mode Exit fullscreen mode

Notice how each added level requires only an added argument to product.