3

I have below code, would like to know what is the best simple and elegant way to express multiple for loop?

for x in range (10):
    for y in range (10):
        for z in range(10):
            if x+y+z=10:
                print (x,y,z)

Thanks in advance!

1
  • There Are solutions.But This code is better readable. Commented Dec 7, 2019 at 14:15

1 Answer 1

5
from itertools import product

for x, y, z in product(range(10), range(10), range(10)):
    if x + y + z == 10:
        print(x, y, z)

To remove range(10) duplication use this:

for x, y, z in product(range(10), repeat=3):

EDIT: as Tomerikoo pointed out - in this specific case the code will be more flexible if you don't unpack the tuple:

for numbers in product(range(10), repeat=3):
    if sum(numbers) == 10:
        print(*numbers)
Sign up to request clarification or add additional context in comments.

6 Comments

product(range(10), times=3). The whole point of the times argument is to avoid repeating the range you want to use multiple times.
to make it more generic regardless of number of loops can be: for prod in product(range(10), times=n): if sum(prod) == 10: print. where n is the number of loops
@Tomerikoo No; again, product has a times argument to avoid that kind of convoluted argument construction.
I get: TypeError: 'times' is an invalid keyword argument for product() maybe you meant repeat
@chepner what if now you want to check it for 2 or 4 numbers? you need to go and add/remove variables and change the if expression. My suggestion simply makes it without the use of variables to better handle future changes
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.