EX:
list1 = [1,2,3,4,5]
list2 = [1,2,8,4,6]
# Now we want to get the duplicates
# ...
# Add them to a list:
duplicates = [1,2,4]
I tried to search but I only found how to remove the duplicates.
CodePudding user response:
By converting one of the lists to a set prior to picking members, this operation will run in linear time - rather than in quadratic time.
That can make a huge difference if both lists starts to get to the hundreds of thousands of items:
set1 = set(list1)
duplicates = [item for item in list2 if item in set1]
otherwise, for just a handful of items, a simple filter is enough: duplicates = [item for item in list2 if item in list1]
.
CodePudding user response:
You can use a set
and the .intersection
method. Like this:
list1 = [1,2,3,4,5]
list2 = [1,2,8,4,6]
duplicates = list(set(list1).intersection(list2))
print(duplicates) # => [1, 2, 4]