Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)]
like image 355
pbgnz Avatar asked Jul 14 '17 03:07

pbgnz


People also ask

How do you concatenate two list values in python?

Python's extend() method can be used to concatenate two lists in Python. The extend() function does iterate over the passed parameter and adds the item to the list thus, extending the list in a linear fashion. All the elements of the list2 get appended to list1 and thus the list1 gets updated and results as output.

How do you combine list elements in python?

The most conventional method to concatenate lists in python is by using the concatenation operator(+). The “+” operator can easily join the whole list behind another list and provide you with the new list as the final output as shown in the below example.

How do I combine two lists of elements?

Join / Merge two lists in python using + operator In python, we can use the + operator to merge the contents of two lists into a new list. For example, We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2.


2 Answers

[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.

like image 66
perigon Avatar answered Oct 12 '22 21:10

perigon


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)))
like image 37
A Monad is a Monoid Avatar answered Oct 12 '22 20:10

A Monad is a Monoid