Permutation of two lists

Question:

I have two lists:

first = ["one", "two", "three"]
second = ["five", "six", "seven"]

I want every single combination of those two lists but with elements from the first list always to be in front. I tried something like this:

for i in range(0, len(combined) + 1):
    for subset in itertools.permutations(combined, i):
        print('/'.join(subset))

Where “combined” was these two list combined but that gave me all of the possibilities and i just want those where elements from the first list are in the first place. For example:

["onefive","twosix","twofive"]

etc.
Does anyone have an Idea how could I make this?

Asked By: WholesomeGhost

||

Answers:

This should do what you’re looking for:

>>> ["/".join(x) for x in itertools.product(first, second)]
['one/five', 'one/six', 'one/seven', 'two/five', 'two/six', 'two/seven', 'three/five', 'three/six', 'three/seven']
>>> 

You can also do it without itertools:

>>> [x + "/" + y for x in first for y in second]
['one/five', 'one/six', 'one/seven', 'two/five', 'two/six', 'two/seven', 'three/five', 'three/six', 'three/seven']
>>> 
Answered By: Tom Karzes

Sometimes using normal loops is the easiest:

["{}/{}".format(j,k) for j in first for k in second]

>>> ['one/five', 'one/six', 'one/seven', 'two/five', 'two/six', 
     'two/seven', 'three/five', 'three/six', 'three/seven']
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.