Vadim Katsemba
Vadim Katsemba

Reputation: 127

Join elements of two lists in Python

Say I have two Python lists containing strings that may or may not be of the same length.

list1 = ['a','b']
list2 = ['c','d','e']

I want to get the following result:

l = ['a c','a d','a e','b c','b d','b e']

The final list all possible combinations from the two lists with a space in between them.

One method I've tried is with itertools

import itertools
for p in itertools.permutations(, 2):
     print(zip(*p))

But unfortunately this was not what I needed, as it did not return any combinations at all.

Upvotes: 0

Views: 628

Answers (4)

Krishna Singhal
Krishna Singhal

Reputation: 661

One-Liner Solution, Use list comprehension and add the items of list

list1 = ['a','b']
list2 = ['c','d','e']
print([i+j for i in list1 for j in list2])

Upvotes: 0

Arrow
Arrow

Reputation: 11

This is another possible method:

list1=['a','b']
list2=['c','d','e']
list3=[]
for i in list1:
    for j in list2:
        list3.append(i+" "+j)
print(list3)

Upvotes: 1

Vespene Gas
Vespene Gas

Reputation: 3760

What you want is a cartesian product.

Code:

import itertools

list1 = ['a', 'b']
list2 = ['c', 'd', 'e']

l = ['%s %s' % (e[0], e[1]) for e in itertools.product(list1, list2)]
print(l)

result:

['a c', 'a d', 'a e', 'b c', 'b d', 'b e']

Upvotes: 1

Shivam Jha
Shivam Jha

Reputation: 4482

First make all possible combinations of the two lists, then use list comprehension to achieve the desired result:

list1 = ['a', 'b']
list2 = ['c', 'd', 'e']


com = [(x,y) for x in list1 for y in list2]
print([a + ' ' + b for (a, b) in com]) # ['a c', 'a d', 'a e', 'b c', 'b d', 'b e']

Upvotes: 1

Related Questions