-4

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

Gianni Spear
  • 6,483
  • 19
  • 74
  • 122

2 Answers2

1

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),
 ....
Ondrej Sika
  • 1,685
  • 2
  • 9
  • 12
0

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.

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
Patrick Bassut
  • 3,233
  • 5
  • 28
  • 53