How can I concatenate all of the responses from (Python's) iter_tools.product()?

Question:

I’m trying generate a list of all possible combinations of characters over a several lengths using Python 2.7. For the sake of example, I’m using a much smaller subset to proof the concept.

Below I generate all combinations of the letters from A-C, of lengths 1 and 2. I then try to generate one list using a second for loop in the same generator comprehension (wrong term?). I can get all of the strings of a single length into a list, but I get the error an integer is required when trying

How do I concatenate all these responses from each of the levels of repeat in the product generator function?

>>> l
['A', 'B', 'C']
>>> p1 = (''.join(p) for p in product(l, repeat=1))
>>> p2 = (''.join(p) for p in product(l, repeat=2))
>>> [str(i) for i in p1]
['A', 'B', 'C']
>>> [str(i) for i in p2]
['AA', 'AB', 'AC', 'BA', 'BB', 'BC', 'CA', 'CB', 'CC']
>>> pn = (''.join(p) for p in product(l, repeat=i) for i in range(1,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required

Yes, I could do this with nested for loops. I’m trying to do it with one-liners, since I saw a similar example with what looked like a generator comprehension. I’ve used list comprehensions before – but when I feed it nested list comprehensions, I get lists of long strings of the entire lists of combinations smashed together.

It could also be that I don’t understand iterator functions correctly, because I struggled to get those debug list comprehensions correct on lines 5 and 7 in my code example.

Asked By: user3.1415927

||

Answers:

You have you for-loops the wrong way around in your generator expression, they “nest” from left to right:

>>> g = (''.join(p) for i in range(1, 3) for p in product(l, repeat=i))
>>> list(g)
['A', 'B', 'C', 'AA', 'AB', 'AC', 'BA', 'BB', 'BC', 'CA', 'CB', 'CC']
Answered By: Joe Iddon