Find combinations without changing order

Question:

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]
                )
Asked By: shantanuo

||

Answers:

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
Answered By: j1-lee
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.