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?
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.
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.
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