as3rdaccount
as3rdaccount

Reputation: 3951

How to perform list comprehension on the following two lists?

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

Upvotes: 0

Views: 65

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180482

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']

Upvotes: 1

jh314
jh314

Reputation: 27812

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

couples = [x + ' and ' + y for x, y in zip(list1, list2)] 

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117981

>>> 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']

Upvotes: 4

Related Questions