pbgnz
pbgnz

Reputation: 497

How to concatenate element-wise two lists of different sizes in Python?

I have two lists of strings and I want to concatenate them element-wise to create a third list

This third list should contain all elements of list_1 as they are, and add new elements for each combination possible of elements list_1+list_2

Note that the two lists do not necessarily have the same length

example:

base = ['url1.com/','url2.com/', 'url3.com/',...]

routes = ['route1', 'route2', ...]

urls = ['url1.com/' + 'url1.com/route1', 'url1.com/route2', 'url2.com/', 'url2.com/route1', 'url2.com/route2', ...]

I tried using the zip method, but without success

urls = [b+r for b,r in zip(base,routes)]

Upvotes: 6

Views: 2918

Answers (2)

developer_hatch
developer_hatch

Reputation: 16224

You can make a product of all of them, and then join them it in a new list:

import itertools
base = ['url1.com/','url2.com/', 'url3.com/']

routes = ['route1', 'route2']

products = [base,routes]

result = []
for element in itertools.product(*products):
    result.append(element[0] + element[1])

print(result)

['url1.com/route1', 'url1.com/route2', 'url2.com/route1', 'url2.com/route2', 'url3.com/route1', 'url3.com/route2']

more python way:

print(list(element[0] + element[1] for element in itertools.product(*products)))

Upvotes: 1

perigon
perigon

Reputation: 2095

[x + y for x in list_1 for y in [""] + list_2]

produces output:

['url1.com/',
 'url1.com/route1',
 'url1.com/route2',
 'url2.com/',
 'url2.com/route1',
 'url2.com/route2',
 'url3.com/',
 'url3.com/route1',
 'url3.com/route2']

BTW, the term you're looking for is Cartesian Product (with a slight modification) rather than elementwise concatenation, since you're going for each possible combination.

Upvotes: 6

Related Questions