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:
JavaScript
x
4
1
assert get_values_in_common([5, 1, 2, 3], [3, 4, 5, 5]) == {3, 5}
2
assert get_values_in_common([1, 2], [2, 2, 3]) == {2}
3
assert get_values_in_common(["tomato", "mango", "kiwi"], ["eggplant", "tomato", "broccoli"]) == {"tomato"}
4
Here’s the code I’m having trouble with:
JavaScript
1
7
1
def get_values_in_common(x, y):
2
list = ""
3
for a in x:
4
if a in x and a in y:
5
list.append(a)
6
return list
7
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 = ""
?):
JavaScript
1
2
1
AttributeError: 'str' object has no attribute 'append'
2
Advertisement
Answer
If you want to use append()
then you have to use list
JavaScript
1
2
1
list = []
2
If you use string list = ""
then you can only concatenate strings
JavaScript
1
2
1
list = list + str(a)
2
But you need set
as answer then you should use list = set()
and add(a)
JavaScript
1
9
1
def get_values_in_common(x, y):
2
result = set()
3
4
for a in x:
5
if a in y: # there is no need to check `if a in x`
6
result.add(a)
7
8
return result
9
But you can do the same shorter
JavaScript
1
3
1
def get_values_in_common(x, y):
2
return set(x) & set(y)
3
And this is why set()
can be very useful.