def common_elements(list1, list2):
"""
Return a list containing the elements which are in both list1 and list2
>>> common_elements([1,2,3,4,5,6], [3,5,7,9])
[3, 5]
>>> common_elements(["this","this","n","that"],["this","not","that","that"])
['this', 'that']
"""
result = []
for element in list1:
if element in list2:
result.append(element)
return result
I have this so far but it returns with duplicates for example:
common_elements(["this","this","n","that"],["this","not","that","that"])
Returns as: ['this', 'this', 'that']
Using set.intersection()
because it means that it is not necessary to convert list2
to a set
def common_elements(list1, list2):
return set(list1).intersection(list2)
It is more efficient to choose the shorter list to convert to a set
def common_elements(list1, list2):
short_list, long_list = sorted((list1, list2), key=len)
return set(short_list).intersection(long_list)
of course to return a list, you would use
return list(set(...))
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