Skip to content
Advertisement

How do I generate all permutations of a list?

How do I generate all the permutations of a list? For example:

JavaScript

Advertisement

Answer

Use itertools.permutations from the standard library:

JavaScript

Adapted from here is a demonstration of how itertools.permutations might be implemented:

JavaScript

A couple of alternative approaches are listed in the documentation of itertools.permutations. Here’s one:

JavaScript

And another, based on itertools.product:

JavaScript
Advertisement