KaliMa
KaliMa

Reputation: 2060

Get a list of N items with K selections for each element?

For example if I have a selection set K

K = ['a','b','c']

and a length N

N = 4

I want to return all possible:

['a','a','a','a']
['a','a','a','b']
['a','a','a','c']
['a','a','b','a']
...
['c','c','c','c']

I can do it with recursion but it is not interesting. Is there a more Pythonic way?

Upvotes: 3

Views: 67

Answers (1)

Blair
Blair

Reputation: 6693

That can be done with itertools.

>>> K = ['a','b','c']
>>> import itertools
>>> N = 4
>>> i = itertools.product(K,repeat = N)
>>> l = [a for a in i]
>>> l[:3]
[('a', 'a', 'a', 'a'), ('a', 'a', 'a', 'b'), ('a', 'a', 'a', 'c')]

EDIT: I realized you actually want product, not combinations_with_replacement. Updated code.

Upvotes: 7

Related Questions