-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
  • 7,033
  • 22
  • 82
  • 131
  • The previous duplicate was completely wrong for this question. It's important to understand terminology properly in order to do research. – Karl Knechtel Feb 18 '23 at 16:48

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,715
  • 2
  • 11
  • 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
  • 115,751
  • 26
  • 228
  • 437
Patrick Bassut
  • 3,310
  • 5
  • 31
  • 54