-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]
                )
SuperStormer
  • 4,997
  • 5
  • 25
  • 35
shantanuo
  • 31,689
  • 78
  • 245
  • 403
  • 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
  • Does this answer your question? [Get the cartesian product of a series of lists?](https://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists) – SuperStormer Nov 21 '22 at 03:38

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
  • 13,764
  • 3
  • 14
  • 26