Raymond Timmermans Raymond Timmermans - 6 months ago 11
Python Question

Go through every possible combination of an array python

Say you got an array of 4 numbers. What is the best way to go through all the possible combinations? A start of the combinations would be:

1,2,3,4

1,2,4,3

1,3,2,4

1,3,4,2

1,4,2,3

2,1,3,4

etc.

Answer

itertools.permutations is just what you're looking for:

>>> from itertools import permutations
>>> [i for i in permutations(range(1, 5), 4)]
[(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)]