0

With four letters in a list

letters = ['a', 'b', 'c', 'd']

I would like to create another list with every letter in a combination so the result would look like:

['a-b', 'a-c', 'a-d'
'b-a', 'b-c', 'b-d',
'c-a', 'c-b', 'c-d',
'd-a', 'd-b', 'd-c']

How can it be done?

alphanumeric
  • 17,967
  • 64
  • 244
  • 392

5 Answers5

6

The itertools.permutations function does exactly that

from itertools import permutations

letters = ["a", "b", "c", "d"]

print(["-".join(perm) for perm in permutations(letters, 2)])

If you don't care about ordering (so a-b would be the same as b-a) then use itertools.combinations

Matteo Zanoni
  • 3,429
  • 9
  • 27
2

Look into permutations :

import itertools 

permutations = list(itertools.permutations(['a', 'b', 'c', 'd'], 2))
permutations = [elem[0]+"-"+elem[1] for elem in permutations]

This achieves the same as the following, which you may be more familiar with :

permutations = []
for letter_1 in letters:
    for letter_2 in letters:
        if letter_1 != letter_2:
            permutations.append(letter_1 + "-" + letter_2)
Charles Dupont
  • 995
  • 3
  • 9
2

As others have noted, there's a standard library function to generate all given-length permutations from a list:

import itertools
combo = [ '-'.join(pair) for pair in itertools.permutations(letters,2) ]

For pairs from short lists, the basic list comprehension option is not too bad (but still second-best):

combo = [ f+'-'+s for fx,f in enumerate(letters) for sx, s in enumerate(letters) if fx!=sx ]
Joffan
  • 1,485
  • 1
  • 13
  • 18
2

The you're looking to make all combinations of the elements of an array as suggested by @quamrana this can be done via itertools.permutation

This function takes the list and the length of the permutation as an input and returns a iterator.

So you need to call

perms = itertools.permutations(['a', 'b', 'c', 'd'], 2)

to get the iterator

Now you can iterate over it and add dashes in the middle via

result = [i[0]+"-"+i[1] for i in perms]
kinshukdua
  • 1,944
  • 1
  • 5
  • 15
1

You're probably looking to use the itertools.permutations() function:

>>> import itertools
>>> res = [f"{i[0]}-{i[1]}" for i in itertools.permutations(letters, 2)]
>>> res
['a-b', 'a-c', 'a-d', 'b-a', 'b-c', 'b-d', 'c-a', 'c-b', 'c-d', 'd-a', 'd-b', 'd-c']
Jacob Lee
  • 4,405
  • 2
  • 16
  • 37