3

I am currently working on a simple project on my own, and I stumbled on a problem:
I need to have a list of 4 numbers: say

L=[1,3,4,6]  

I need a full list of rearrangements of the Numbers so:

L_arranged=[[1,3,4,6],[1,3,6,4],[1,6,3,4],...,[3,4,1,6]]  

Any Ideas?
Even a theory would be useful, thank you :)

Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61
Eric Lee
  • 230
  • 1
  • 2
  • 13

1 Answers1

5

You're looking for itertools.permutations.

>>> from itertools import permutations
>>> [list(p) for p in permutations([1,3,4,6])]
[[1, 3, 4, 6], [1, 3, 6, 4], [1, 6, 3, 4], ..., [3, 4, 1, 6]]

If you don't need to mutate (edit) the results, you can cast the return straight to a list, yielding tuples

>>> list(permutations([1,3,4,6]))
[(1, 3, 4, 6), (1, 3, 6, 4), (1, 6, 3, 4), ..., (3, 4, 1, 6)]

Even faster, if you plan on using the results solely as an iterator, you don't need to cast it at all

>>> for p in permutations([1,3,4,6]):
...     print(p)
(1, 3, 4, 6)
(1, 3, 6, 4)
(1, 6, 3, 4)
    ...
(3, 4, 1, 6)
Valkyrie
  • 841
  • 1
  • 9
  • 22