8

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?

1
  • Just as a side note, this is not a forum but a question and answer site :) Commented Mar 26, 2014 at 7:17

4 Answers 4

12

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']
Sign up to request clarification or add additional context in comments.

1 Comment

This just returns a map object
7
List_C = ['{} {}'.format(x,y) for x,y in zip(List_A,List_B)]

2 Comments

I prefer this answer because of its clarity, even though it may be slower than the mapping approach.
@holdenweb: I usually stick with this method in case some of the array values are not strings.
0

If list_a and list_b has same length always then try it:

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 may 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)

Comments

0

One way to solve this problem is as below:

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 will get on executing the above code is:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.