This will be the first of what I’m going to try to be a daily series of small tips and tricks in Python.
We have two lists:
A = [1, 2, 3, 4, 5, 6] and B = [10, 9, 8, 7, 6, 5]
To get the elements that are in both lists:
def intersect(*lists): return reduce(set.intersection, lists)
The only trick is to actually pass the lists to the function not as lists but as sets. [EDIT: This can be done before the function call or just change the function to what Paddy wrote on the 1st comment] Bad part: if the lists contain duplicate elements, there they go. Sets only contain unique items. Which, by the way, leads to another question “What if I want to eliminate duplicates from a list?”:
newlist = set(oldlist)