Two word lists intersect in python

I want to find the intersection of two lists in python. I have something similar to this:

>>> q = ['apple', 'peach', 'pear', 'watermelon', 'strawberry']
>>> w = ['pineapple', 'peach', 'watermelon', 'kiwi']

and I want to find something similar to this:

t = ['peach', 'watermelon']

I know its simple, question, but I'm new to python - does anyone have any suggestions?

+5
source share
3 answers

The intersection () method is available for sets , which can be easily made from lists.

ETA: if you need a list from it ...

q = ['apple', 'peach', 'pear', 'watermelon', 'strawberry']
w = ['pineapple', 'peach', 'watermelon', 'kiwi']
t = list(set(q) & set(w))

Now t is:

['watermelon', 'peach']
+10
source

The preferred way to do this is to set the intersection :

list(set(q) & set(w))

If the lists are short, use the list .

t = [x for x in q if x in w]

, O(n^2), .

+4

, intersection , :

q = ['apple', 'peach', 'pear', 'watermelon', 'strawberry']
w = ['pineapple', 'peach', 'watermelon', 'kiwi']
set(q).intersection(w)
+1
source

All Articles