Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate element-wise two lists in Python

Tags:

python

list

I have two lists and I want to concatenate them element-wise. One of the list is subjected to string-formatting before concatenation.

For example :

a = [0, 1, 5, 6, 10, 11]  b = ['asp1', 'asp1', 'asp1', 'asp1', 'asp2', 'asp2'] 

In this case, a is subjected to string-formatting. That is, new a or aa should be :

aa = [00, 01, 05, 06, 10, 11] 

Final output should be :

c = ['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211'] 

Can somebody please tell me how to do that?

like image 922
Sanchit Avatar asked Oct 24 '13 07:10

Sanchit


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 concatenate a list of elements in Python?

Python concatenate lists without duplicates The list and the new list are concatenated by using the “+” operator. The print(list) is used to get the output.


2 Answers

Use zip:

>>> ["{}{:02}".format(b_, a_) for a_, b_ in zip(a, b)] ['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211'] 
like image 173
orlp Avatar answered Sep 23 '22 02:09

orlp


Using zip

[m+str(n) for m,n in zip(b,a)] 

output

['asp10', 'asp11', 'asp15', 'asp16', 'asp210', 'asp211'] 
like image 32
RMcG Avatar answered Sep 19 '22 02:09

RMcG