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)]
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.
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.
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.
[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.
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With