-1

I have two lists:

list1 = ["red", "green", "blue", "yellow"]
list2 = ["car", "tree", "house", "guitar"]

My desired output is a new list:

list3 = ["red house", "red guitar", "red tree", "red car", "green house", "green guitar" etc]

I guess I need a for loop that iterates through list 1 and combines the i with the value/index in list 2 (and adding a string " "). But I can't figure out how to do that without getting errors.

Thank you for your help.

Thierno Amadou Sow
  • 2,523
  • 2
  • 5
  • 19
  • 1
    Please update your question with your code that gives you errors. Please also include the full error traceback. – quamrana Apr 03 '22 at 15:17

2 Answers2

7

Try this

list1 = ["red", "green", "blue", "yellow"] 

list2 = ["car", "tree", "house", "guitar"]

list3 = []

for i in list1:
    for j in list2:
        list3.append(i+" "+j)

or in more pythonic way

list1 = ["red", "green", "blue", "yellow"] 

list2 = ["car", "tree", "house", "guitar"]

list3 = [i+" "+j for i in list1 for j in list2]
Thierno Amadou Sow
  • 2,523
  • 2
  • 5
  • 19
  • 1
    For sure the second way is more pythonic, even if there are two for loops into the comprehension. +1 – FLAK-ZOSO Apr 03 '22 at 15:31
  • 1
    I always refer to this [answer](https://stackoverflow.com/a/45079294) for a visual way of converting between nested for loops and a list comprehension. (+1 btw) – quamrana Apr 03 '22 at 15:34
2

As an alternative solution you can use itertools.product like below:

>>> import itertools

>>> list1 = ["red", "green", "blue", "yellow"] 
>>> list2 = ["car", "tree", "house", "guitar"]

>>> list(itertools.product(*[list1 , list2]))
[('red', 'car'),
 ('red', 'tree'),
 ('red', 'house'),
 ('red', 'guitar'),
 ('green', 'car'),
 ('green', 'tree'),
 ('green', 'house'),
 ('green', 'guitar'),
 ('blue', 'car'),
 ('blue', 'tree'),
 ('blue', 'house'),
 ('blue', 'guitar'),
 ('yellow', 'car'),
 ('yellow', 'tree'),
 ('yellow', 'house'),
 ('yellow', 'guitar')]

>>> list(map(' '.join , (itertools.product(*[list1 , list2]))))
['red car',
 'red tree',
 'red house',
 'red guitar',
 'green car',
 'green tree',
 'green house',
 'green guitar',
 'blue car',
 'blue tree',
 'blue house',
 'blue guitar',
 'yellow car',
 'yellow tree',
 'yellow house',
 'yellow guitar']

You can use this solution for more than two lists:

>>> list1 = ["red", "green"] 
>>> list2 = ["car", "tree"]
>>> list3 = ["here", "there"]
>>> list(map(' '.join , (itertools.product(*[list1 , list2, list3]))))
['red car here',
 'red car there',
 'red tree here',
 'red tree there',
 'green car here',
 'green car there',
 'green tree here',
 'green tree there']
I'mahdi
  • 23,382
  • 5
  • 22
  • 30