0

This question has probably been asked here before but me being new to python and lack of better keywords to search led me to ask the question.

I have two lists:

list1 = ['John', 'Don', 'Sam']
list2 = ['Melissa', 'Amber', 'Liz']
couples = [x + ' and ' y for x in list1 y in list2] # I can't do that

My couples list should look like this:

['John and Melissa', 'Don and Amber', 'Sam and Liz']

How do I concatenate this two lists that way?

Thanks in advance

as3rdaccount
  • 3,613
  • 10
  • 36
  • 59
  • possible duplicate of [How can I iterate through two lists in parallel in Python?](http://stackoverflow.com/questions/1663807/how-can-i-iterate-through-two-lists-in-parallel-in-python) – Roger Fan Aug 21 '14 at 19:59

3 Answers3

4
>>> list1 = ['John', 'Don', 'Sam']
>>> list2 = ['Melissa', 'Amber', 'Liz']
>>> [' and '.join(i) for i in zip(list1, list2)]
['John and Melissa', 'Don and Amber', 'Sam and Liz']
Cory Kramer
  • 107,498
  • 14
  • 145
  • 201
1

You can use zip() to iterate through both lists:

couples = [x + ' and ' + y for x, y in zip(list1, list2)] 
BrenBarn
  • 228,001
  • 34
  • 392
  • 371
jh314
  • 25,902
  • 15
  • 60
  • 80
1

zip both lists and use str.format

list1 = ['John', 'Don', 'Sam']
list2 = ['Melissa', 'Amber', 'Liz']
print ["{} and {}".format(*name) for name in zip(list1,list2)]
['John and Melissa', 'Don and Amber', 'Sam and Liz']

You can also use enumerate:

list1 = ['John', 'Don', 'Sam']
list2 = ['Melissa', 'Amber', 'Liz']
print ["{} and {}".format(name,list2[ind]) for ind, name in enumerate(list1)]
['John and Melissa', 'Don and Amber', 'Sam and Liz']
Padraic Cunningham
  • 168,988
  • 22
  • 228
  • 312