Reputation: 23
I have 2 lists like so:
list1 = ['Apples', 'Bananas', 'Oranges']
list2 = ['Oranges', 'Grapes', 'Strawberries', 'Apples']
'Apples' and 'Oranges' are in both lists - is there a function in python that will enable me to print the matching strings in both lists?
Upvotes: 2
Views: 43
Reputation: 24049
You can use set.intersection
.
>>> list(set(list1).intersection(list2))
['Oranges', 'Apples']
>>> set(list1).intersection(list2)
{'Apples', 'Oranges'}
Upvotes: 3
Reputation: 3130
Use list comprehension:
list1 = ['Apples', 'Bananas', 'Oranges']
list2 = ['Oranges', 'Grapes', 'Strawberries', 'Apples']
[item for item in list1 if item in list2]
Output:
['Apples', 'Oranges']
Upvotes: 1