Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a list containing common elements with no duplicates

Tags:

python

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']

like image 468
Kramet Avatar asked May 18 '11 01:05

Kramet


1 Answers

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(...))
like image 159
John La Rooy Avatar answered Oct 13 '22 10:10

John La Rooy