6

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?

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
TheRealFakeNews
  • 7,512
  • 16
  • 73
  • 114

1 Answers1

6

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.

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186