MattoTodd
MattoTodd

Reputation: 15209

Python - Get list of every permutation of a list of a set number of characters

I have a list of 7 characters. How would I programmatically create every permutation of the the letters shuffled (I know that the number of lists would be 7 factorial).

I know how to shuffle a list, but I assume that wouldn't be efficient to just keep shuffling the list, and then checking if i've already created that permutation and keep going til I hit the number of possibilities.

Upvotes: 0

Views: 385

Answers (2)

Greg Hewgill
Greg Hewgill

Reputation: 992857

Use itertools.permutations:

>>> list(itertools.permutations("abc"))
[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]

Upvotes: 7

srgerg
srgerg

Reputation: 19329

Couldn't you use the permutations function from the itertools module?

Upvotes: 1

Related Questions