Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

intersect two lists of words in python

Tags:

python

list

i want to find the intersection of two lists in python. i have something that looks like this:

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

and i want to find something that looks like this:

t = ['peach', 'watermelon']

i know its a simple, question but im new to python--does anyone have any suggestions?

like image 444
user808545 Avatar asked Jun 21 '11 19:06

user808545


3 Answers

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

ETA: if you want a list out of it...

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

Now t is:

['watermelon', 'peach']
like image 68
Turnsole Avatar answered Sep 26 '22 02:09

Turnsole


The preferred way of doing it is via set intersection:

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

If the lists are short, a list comprehension should work.

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

However, beware, this is O(n^2), so it is not very efficient with long lists.

like image 28
Kimvais Avatar answered Sep 25 '22 02:09

Kimvais


It was discussed here on SO that intersection works a bit faster, so you can use:

q = ['apple', 'peach', 'pear', 'watermelon', 'strawberry']
w = ['pineapple', 'peach', 'watermelon', 'kiwi']
set(q).intersection(w)
like image 39
Artsiom Rudzenka Avatar answered Sep 24 '22 02:09

Artsiom Rudzenka