Concatenate strings from the cartesian product of two list (preferably without for loop)

Viewed 169

Using a for loop to iterate and concatenate words to create several permutations. My for loop works but I'd rather not use a for loop as I want to have the code on one line so I can create a variable.

What options do I have? Basic question I realize.

Here's the two lists I want to concatenate:

first = ["Happy", "Sad", "Fun"]
second = ["Game", "Movie"]

desired output:

combo = ["Happy Game", "Happy Movie", "Sad Game", "Sad Movie", "Fun Game", "Fun Movie"]

This for loop works but I want it on one line and as a variable:

for b in first:
    for s in second:
        combo = b + ' ' + s
        print(combo)

Is there a way to do this without a for loop?

2 Answers

You can use itertools.product(), map() and str.join to achieve this result without using for loop (not even within list comprehension) as:

>>> from itertools import product

>>> first = ["Happy", "Sad", "Fun"]
>>> second = ["Game", "Movie"]

>>> map(' '.join, product(first, second))
['Happy Game', 'Happy Movie', 'Sad Game', 'Sad Movie', 'Fun Game', 'Fun Movie']

Here itertools.product() returns the cartesian product of your iterables.

Refer below documents for more details:

As mentioned in the comments, a list comprehension is the way to do this in a one-liner:

combos = [b + ' ' + s for b in first for s in second]

This basically ends up doing the same as this:

combos = []

for b in first:
    for s in second:
        combos.append(b + ' ' + s)

The result:

>>> combos
['Happy Game', 'Happy Movie', 'Sad Game', 'Sad Movie', 'Fun Game', 'Fun Movie']

See here for more information on list comprehensions: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

Related