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?
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']
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With