Home > database >  How to merge the values of list1 with list 2?
How to merge the values of list1 with list 2?

Time:04-05

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.

CodePudding user response:

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]

CodePudding user response:

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']
  • Related