7

I have a set of 6 items, lets call them "1" to "6". What I want to do is create another list with all possible combinations (orders?) of these items. Means in every possible combination, all 6 items have to be included and there cant be duplicates. It may be a combination backwards, since its a different set of numbers.

Heres my idea:

import random

items = [1,2,3,4,5,6]
ListOfCombinations = []
while True:
    random.shuffle(items)
    print(items)
    string = " ".join(str(e) for e in items)
    if string not in ListOfCombinations:
        ListOfCombinations.append(string)

What I tried to do here is create a random order and add it into the second list if its not already inside. But I feel like there has to be a different way of doing and I probably did it wrong to. I'm a noob at python so help would be appreciated!

diatomym
  • 163
  • 1
  • 2
  • 11

1 Answers1

17

You are looking for permutations() from the itertools library.

from itertools import permutations

# this will create all permutations of [0,1,2]
list(permutations(range(3)))

# returns:
[(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]
Nick McCurdy
  • 17,658
  • 5
  • 50
  • 82
James
  • 32,991
  • 4
  • 47
  • 70