find all possible combination sequences in a list of python

Question:

i have a list in Python

mylist = [0, 1, 2, 3, 4, 5]

where 0 is the start and 5 is the end.
I wish to know if there a way to create all possible sequences between 0 and 5 such as:

mylist1 = [0, 2, 1, 3, 4, 5]
mylist2 = [0, 3, 2, 1, 4, 5]
mylist3 = [0, 4, 3, 2, 1, 5]
mylist4 = [0, 2, 1, 3, 4, 5]
mylist5 = [0, 3, 2, 1, 4, 5]

etc

Asked By: Gianni Spear

||

Answers:

You should use itertools.permutations, like this:

import itertools
gen = itertools.permutations([1, 2, 3, 4, 5, 6])
print gen.next()  # prints (1, 2, 3, 4, 5, 6)
print gen.next()  # prints (1, 2, 3, 4, 6, 5)
print gen.next()  # prints (1, 2, 3, 5, 4, 6)

Keep doing it until StopIteration is raised.

Answered By: Patrick Bassut

You can use itertools.permutations

In [1]: import itertools

In [2]: l = [0, 1, 2, 3, 4, 5]

In [3]: tuple(itertools.permutations(l))
Out[3]: 
((0, 1, 2, 3, 4, 5),
 (0, 1, 2, 3, 5, 4),
 (0, 1, 2, 4, 3, 5),
 (0, 1, 2, 4, 5, 3),
 (0, 1, 2, 5, 3, 4),
 ....
Answered By: Ondrej Sika
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.