1

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?

I'mahdi
  • 23,382
  • 5
  • 22
  • 30

1 Answers1

3

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
I'mahdi
  • 23,382
  • 5
  • 22
  • 30