3
\$\begingroup\$

I have the code below to get an infinite generator of the products of an iterable (e.g. for the iterable "ABC" it should return

A, B, C, AA, AB, AC, BA, BB, BC, CA, CB, CC, AAA, AAB, AAC etc.

for product in (itertools.product("ABC", repeat=i) for i in itertools.count(0)):
 for each_tuple in product:
 print(each_tuple)

How would I remove the nested for loop, or is there a better approach?

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Sep 15, 2013 at 12:22
\$\endgroup\$
1
  • 1
    \$\begingroup\$ you can write itertools.count() instead of .count(0). :) \$\endgroup\$ Commented Sep 15, 2013 at 20:05

1 Answer 1

4
\$\begingroup\$

Well, you effectively have 3 nested loops including the generator comprehension, which you can reduce to two just by simplifying:

def get_products(string):
 for i in itertools.count(0):
 for product in itertools.product(string, repeat=i):
 yield product

Or if you are intent on putting it in a single line, use chain:

products_generator = itertools.chain.from_iterable(itertools.product("ABC", repeat=i)
 for i in itertools.count(0))
answered Sep 15, 2013 at 13:11
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.