Search code examples
pythonlistsequence

find all possible combination sequences in a list of python


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


Solution

  • 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),
     ....