Skip to content
Advertisement

Output Common Elements of Two Lists using Sets

I’d like to write a function definition that takes two lists and returns a single set with the values that each list has in common.

Formally, here are some assertions I’d like to pass:

assert get_values_in_common([5, 1, 2, 3], [3, 4, 5, 5]) == {3, 5}
assert get_values_in_common([1, 2], [2, 2, 3]) == {2}
assert get_values_in_common(["tomato", "mango", "kiwi"], ["eggplant", "tomato", "broccoli"]) == {"tomato"}

Here’s the code I’m having trouble with:

def get_values_in_common(x, y):
    list = ""
    for a in x:
        if a in x and a in y:
            list.append(a)
    return list

I receive an error output that I know has to do with strings and integers, but am unsure what exactly the problem is. (Maybe it’s that I make the above list by saying list = ""?):

AttributeError: 'str' object has no attribute 'append'

Advertisement

Answer

If you want to use append() then you have to use list

 list = []

If you use string list = "" then you can only concatenate strings

 list = list + str(a)

But you need set as answer then you should use list = set() and add(a)

def get_values_in_common(x, y):
    result = set()

    for a in x:
        if a in y: # there is no need to check `if a in x`
            result.add(a)

    return result

But you can do the same shorter

def get_values_in_common(x, y):
    return set(x) & set(y)

And this is why set() can be very useful.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement