how to avoid nested loop in python and check condition on all combination of elements in multi list

Viewed 43

I do have the following n=3 list (nested loops) I need it to be general and works for any n lists

object1 = [4, 5, 3]
object2 = [1, 2, 3, 4]
object3 = [1, 0]

for c1 in object1:
    for c2 in object2:
        for c3 in object3:
            if c1+c2+c3<9:
                print(c1,c2,c3)

How can I do it in an efficient way in Python?

1 Answers

You need itertools.product:

import itertools
for cs in itertools.product(*[object1, object2, object3]):
    if sum(cs) < 9:
        print(cs[0], cs[1], cs[2])

# OR
# for c1, c2, c3 in itertools.product(*[object1, object2, object3]):
#     if (c1+c2+c3) < 9:
#         print(c1,c2,c3)

Output:

4 1 1
4 1 0
4 2 1
4 2 0
4 3 1
4 3 0
4 4 0
5 1 1
5 1 0
5 2 1
5 2 0
5 3 0
3 1 1
3 1 0
3 2 1
3 2 0
3 3 1
3 3 0
3 4 1
3 4 0
Related