Search code examples
pythonfor-loopnested-loops

Flatten nested for loop with dependent variables


I want to perform:

for i in list_a:
    for j in list_b[i]:
        print(i, j)

Is it possible to do it using itertools? I am looking for something like:

for i, j in itertools.product(list_a, list_b[i])

I want to do that for speed and readability.


Solution

  • itertools won't give you speed in most cases (but will give you stability and save you time so use it whenever possible) as for both readability and speed - nothing beats list comprehension :

    your_list = [(i, j) for i in list_a for j in list_b[i]]
    

    Then you can print it if you wish :)