0

Say if

list1 = ['apple', 'orange', 'grape']
list2 = ['pineapple', 'banana', 'pear']

how could you add them so that

list3 = ['apple pineapple', 'orange banana', 'grape pear']

Using a for statement inside a for statement I can get this out:

applepineapple
applebanana
applepear
orangepineapple
orangebanana
orangepear
grapepineapple
grapebanana
grapepear

Thanks!

3
  • Don't use nested loops, just use a single loop that accesses the ith element of both lists. Commented Dec 9, 2014 at 20:08
  • 2
    What happened to "grape" in the third list, and where did "oranges" come from? Commented Dec 9, 2014 at 20:08
  • Me being silly. Edited. Commented Dec 9, 2014 at 20:14

4 Answers 4

5

There are many ways to do this. One way is a list comprehension with zip:

>>> zip(list1, list2)
[('apple', 'pineapple'), ('orange', 'banana'), ('grape', 'pear')]
>>> ['{} {}'.format(x, y) for x, y in zip(list1, list2)]
['apple pineapple', 'orange banana', 'grape pear']

You can also use concatenation (x + ' ' + y) or interpolation ('%s %s' % (x, y)) to form the strings.

Sign up to request clarification or add additional context in comments.

Comments

2
>>> list1 = ['apple', 'orange', 'grape'] 
>>> list2 = ['pineapple', 'banana', 'pear']
>>> [ list1[x]+ " " +list2[x] for x in range(len(list1))]   # both should must have same length
['apple pineapple', 'orange banana', 'grape pear']

pythonic way:

>>> map(" ".join,zip(list1,list2))
['apple pineapple', 'orange banana', 'grape pear']

Comments

1
print ([' '.join(z) for z in zip(list1,list2)])

Comments

1

You can do it in one line with:

new_list = map(lambda x : x[0]+' '+x[1], zip(list1, list2))

zip() takes two sequences and forms list where the i-th entry is a tuple containing the i-th entry of the first list and the i-th entry of the second list. map(func, sequence) applies a given function to a sequence. These two commands will save you a ton of time working with lists.

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.