jivcodes
jivcodes

Reputation: 23

How do you print matching strings across 2 lists using Python?

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

Answers (2)

I'mahdi
I'mahdi

Reputation: 24049

You can use set.intersection.

>>> list(set(list1).intersection(list2))
['Oranges', 'Apples']

>>> set(list1).intersection(list2)
{'Apples', 'Oranges'}

Upvotes: 3

Michael S.
Michael S.

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

Related Questions