Python - merge 2 lists

Hi, I am new to Python and this forum.

My question is:

I have two lists:

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

I managed to create a list like this using zip :

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

But as a result, I am looking for a list:

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

No matter what I tried, I did not succeed! How can I get this result?

+8
python list concatenation
source share
4 answers

You get the encrypted names from both lists, just attach each pair, for example,

 print map(" ".join, zip(list_a, list_b)) # ['john walker', 'peter smith', 'paul anderson'] 
+12
source share
 List_C = ['{} {}'.format(x,y) for x,y in zip(List_A,List_B)] 
+6
source share

If list_a and list_b are the same length then try:

list_c = [list_a[i]+' '+list_b[i] for i in xrange(0,len(list_a))]

On the other hand, if list_a and list_b can have different lengths, then:

 list_c=[] for i in xrange(0,len(list_a) if len(list_a)>len(list_b) else len(list_b)): merged_item = (list_a[i] if i<len(list_a) else '')+\ (' ' if i<len(list_a) and i<len(list_b) else '')+\ (list_b[i] if i<len(list_b) else '') list_c.append(merged_item) 
0
source share

One way to solve this problem:

 list_d = [] # desired output list list_a = ['john', 'peter', 'paul'] list_b = ['walker', 'smith', 'anderson'] for i in range(len(list_a if len(list_a) < len(list_b) else list_b)): f = " ".join([list_a[i], list_b[i]]) list_d.append(f) print d 

The output you get when you execute the above code:

 ['john walker', 'peter smith', 'paul anderson'] 
0
source share

All Articles