How to concatenate each item in two lists?

Viewed 27

I'm new in Python and for my learning project, I need to create a list that each item from list1 should be combined with each list2 items. Thank you very much!

What I have:

list1=["red", "blue", "green", "yellow", "pink"]
list2=["apple", "orange", "tomato", "mango"]

What I need:

redapple
redorange
redtomato
redmango
blueapple
blueorange
bluetomato
...

I know it is not that complex but I'll appreciate the help!

2 Answers

comphrension way:

list3 = [x+y for x in list1 for y in list2]

basically means:

list3 = []

for x in list1:
    for y in list2:
        list3.append(x+y)

As User Barmar suggested using itertools you can achieve this very simply like this,

Code:

import itertools
list1=["red", "blue", "green", "yellow", "pink"]
list2=["apple", "orange", "tomato", "mango"]

for color,fruit in itertools.product(list1,list2):
    print(color+fruit)

Output:

redapple
redorange
redtomato
redmango
blueapple
blueorange
bluetomato
bluemango
greenapple
greenorange
greentomato
greenmango
yellowapple
yelloworange
yellowtomato
yellowmango
pinkapple
pinkorange
pinktomato
pinkmango
Related