Search code examples
pythonpermutationpython-itertools

Getting permutations in Python, itertools


I want to get all the 3 letter permutations possible from every letter in the alphabet using itertools. This comes back blank:

import itertools 

def permutations(ABCDEFGHIJKLMNOPQRSTUVWXYZ, r=3):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    for indices in product(range(n), repeat=r):
        if len(set(indices)) == r:
            yield tuple(pool[i] for i in indices)

What am I doing wrong?


Solution

  • The code in the itertools.permutations documentation explains how the function is implemented, not how to use it. You want to do this:

    perms = itertools.permutations('ABCDEFGHIJKLMNOPQRSTUVWXYZ', r=3)
    

    You can print them all out by converting it to a list (print(list(perms))), but you can just iterate over them in a for loop if you want to do something else with them - eg,

    for perm in perms:
        ...