I would like to intersect two lists in Python (2.7). I need the result to be iterable:
list1 = [1,2,3,4]
list2 = [3,4,5,6]
result = (3,4) # any kind of iterable
Providing a full iteration will be performed first thing after the intersection, which of the following is more efficient?
Using a generator:
result = (x for x in list1 if x in list2)
Using filter():
result = filter(lambda x: x in list2, list1)
Other suggestions?
Thanks in advance,
Amnon
set(list1).intersection(list2)
is faster thanset(list1) & set(list2)
, i guess it's because the creation of two sets is more expensive than loading and calling.intersection()
hmm .. – Involution