2

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?

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
nia4life
  • 333
  • 1
  • 5
  • 17
  • 3
    `[b + ' ' + s for b in first for s in second]`. Why is this tagged pandas? – Dani Mesejo Dec 28 '20 at 21:43
  • 3
    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) – MYousefi Dec 28 '20 at 21:46
  • A for loop is probably the most straightforward way https://stackoverflow.com/questions/48243018/concatenate-string-to-the-end-of-all-elements-of-a-list-in-python – Alex Dowd Dec 28 '20 at 21:52

2 Answers2

3

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:

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
2

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

Ben Soyka
  • 816
  • 10
  • 25
  • 2
    but list comprehension also contains for loop (if that counts) – Moinuddin Quadri Dec 28 '20 at 22:24
  • 2
    @MoinuddinQuadri That's true I suppose, although I believe OP's main request was for a one-liner that assigns to a variable, so either solution should work fine. There's more than one way to do this I guess. ‍♂️ Great answer though! – Ben Soyka Dec 28 '20 at 22:47