-2

I am trying to generate permutations from this list without changing the order.

mylist = [["a", "b"], ["c", "d"], ["e", "f"], ["g", "h"], ["i"]]

The expected result:

acegi
bcehi
acfgi
bcfhi
adegi
bdehi
adfgi
bdfhi
acegi
bcehi
acfgi
bcfhi
adegi
bdehi
adfgi
bdfhi

This code is working as expected. But I will like to know if there is any other way.

for f in range(2):
    for s in range(2):
        for t in range(2):
            for f in range(2):
                print(
                    mylist[0][f]
                    + mylist[1][s]
                    + mylist[2][t]
                    + mylist[3][f]
                    + mylist[4][0]
                )
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
shantanuo
  • 30,102
  • 75
  • 225
  • 364
  • Does this answer your question? [All combinations of a list of lists](https://stackoverflow.com/questions/798854/all-combinations-of-a-list-of-lists) – Kelly Bundy Jan 28 '22 at 04:19

1 Answers1

2

You can use itertools.product:

import itertools

mylist = [["a", "b"], ["c", "d"], ["e", "f"], ["g", "h"], ["i"]]

for p in itertools.product(*mylist):
    print(''.join(p))

# acegi
# acehi
# acfgi
# acfhi
# adegi
# adehi
# adfgi
# adfhi
# bcegi
# bcehi
# bcfgi
# bcfhi
# bdegi
# bdehi
# bdfgi
# bdfhi
j1-lee
  • 10,540
  • 3
  • 12
  • 22