Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - concatenate 2 lists

Hi I am new to both Python and this forum.

My question:

I have two lists:

list_a = ['john','peter','paul']
list_b = [ 'walker','smith','anderson']

I succeeded in creating a list like this using zip:

list_c = zip(list_a, list_b)
print list_c
# [ 'john','walker','peter','smith','paul','anderson']

But the result I am looking for is a list like:

list_d = ['john walker','peter smith','paul anderson']

Whatever I tried I didn't succeed! How may I get this result?

like image 907
user3460882 Avatar asked Mar 25 '14 17:03

user3460882


People also ask

Can you concatenate two lists 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?

Using join() method to concatenate items in a list to a single string. The join() is an inbuilt string function in Python used to join elements of the sequence separated by a string separator. This function joins elements of a sequence and makes it a string.

How do you merge two lists of strings 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.


2 Answers

You are getting zipped names from both the lists, simply join each pair, like this

print map(" ".join, zip(list_a, list_b))
# ['john walker', 'peter smith', 'paul anderson']
like image 106
thefourtheye Avatar answered Sep 29 '22 04:09

thefourtheye


List_C = ['{} {}'.format(x,y) for x,y in zip(List_A,List_B)]
like image 40
GWW Avatar answered Sep 29 '22 04:09

GWW