Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select elements in the intersection of two lists in Python

Tags:

python

list

As a quick example:

list1 = ['a', 'b', 'c']
list2 = ['a', 'stack', 'overflow']
for i in list1 and list2:
    print i

this prints all the elements in list2. Why is this? How can I just print the elements that are in both lists?

like image 759
TheRealFakeNews Avatar asked Apr 05 '15 02:04

TheRealFakeNews


People also ask

How do you find common items in two lists in python?

Method 2:Using Set's intersection property Convert the list to set by conversion. Use the intersection function to check if both sets have any elements in common. If they have many elements in common, then print the intersection of both sets.


1 Answers

If your lists can be big, its better to convert them to sets and use intersection over them:

list1 = ['a', 'b', 'c']
list2 = ['a', 'stack', 'overflow']

for i in set(list1).intersection(set(list2)):
    print i

In case you want to iterate on that intersection repetitively, save it in a variable of its own (intersect = set(list1).intersection(set(list2))).

You could also use:

for i in list 1:
    if i in list2:
        print i

but the problem of using in in a list for checking membership is that it can be an O(n) operation, so overall, your loop becomes O(n^2). OTOH, using in on a set for membership is O(1), so it is much faster.

As for your original question, when you do for i in list1 and list2, it is interpreted as for i in (list1 and list2), and the value of list1 and list2 is simply list2 if list1 is not empty, so you end up iterating over the second list only.

like image 180
Anshul Goyal Avatar answered Sep 22 '22 11:09

Anshul Goyal