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

Time:07-15

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?

CodePudding user response:

You can use set.intersection.

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

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

CodePudding user response:

Use list comprehension:

list1 = ['Apples', 'Bananas', 'Oranges']
list2 = ['Oranges', 'Grapes', 'Strawberries', 'Apples']
[item for item in list1 if item in list2]

Output:

['Apples', 'Oranges']
  • Related