This question already has an answer here:
i just wrote a function that should print out all the values 2 dictionaries have in common. so if use the following line in my function:
print list_intersection([1, 3, 5], [5, 3, 1])
The output should be:
[1, 3, 5]
I wrote the following code to solve this problem:
def list_intersection(list_1, list_2):
empty_list = []
for number in list_1:
if number in list_2:
return empty_list.append(number)
The problem is that i only get None as output, but if i use the following code:
def list_intersection(list_1, list_2):
empty_list = []
for number in list_1:
if number in list_2:
return number
I get the numbers printed out one by one that are in both lists. I have no idea why my program isn't just putting the numbers both lists have in common into my empty_list and return me my empty_list
I suppose the assertion could be made that this isn't exactly a duplicate. For the reason why
.append()
returnsNone
please see Alex Martelli's erudite answer.For your code instead do:
This avoids the following pitfalls:
None
instead of the list intersection.None
for each element oflist_2
.