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,711
  • 12
  • 42
  • 62
  • 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
  • 114,268
  • 16
  • 167
  • 218
1

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

couples = [x + ' and ' + y for x, y in zip(list1, list2)] 
BrenBarn
  • 242,874
  • 37
  • 412
  • 384
jh314
  • 27,144
  • 16
  • 62
  • 82
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
  • 176,452
  • 29
  • 245
  • 321