Search code examples
pythonpermutationpython-itertools

Long Permutations from Small Lists


I have a list titled outcomes:

outcomes = ["heads", "tails"]

As you can see, the list has two elements.

If I want to get permutations from the list, I use the itertools python package as follows:

import itertools 

for permutation in itertools.permutations(outcomes, 2):
    print(permutation)

This code produces the following output:

('heads', 'tails')
('tails', 'heads')

The problem comes when I try to create permutations that are longer than my list; i.e. permutations with more than 2 elements. For instance if I try permutations of 3 or more elements, I get no output:

for permutation in itertools.permutations(outcomes, 3):
    print(permutation)

Are there any quick workarounds for this?


Solution

  • You're looking for itertools.product. A permutation is an ordering of the existing elements. What you're describing is really a Cartesian product.

    import itertools 
    
    outcomes = ['heads', 'tails']
    for flips in itertools.product(outcomes, repeat=3):
        print(flips)