How to select items at the intersection of two lists in Python

As a quick example:

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

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

+6
source share
1 answer

If your lists can be large, it’s better to convert them to settings and use intersection for them:

 list1 = ['a', 'b', 'c'] list2 = ['a', 'stack', 'overflow'] for i in set(list1).intersection(set(list2)): print i 

If you want to iterate over this intersection, save it in the variable ( intersect = set(list1).intersection(set(list2)) ).

You can also use:

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

but the problem of using in in the list to verify membership is that it could be an O(n) operation, so overall your cycle becomes O (n ^ 2). OTOH, using in for 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 just list2 if list1 is not empty, so you only end the iteration over the second to the list.

+5
source

Source: https://habr.com/ru/post/984696/


All Articles