The return
statement needs to be unindented such that it is placed at the end of the function and not inside the loop:
def intersection(lst1, lst2):
mylist = []
for n in lst1:
for o in lst2:
if n == o:
mylist.append(n)
return mylist
Before, when it was immediately after mylist.append(n)
, the function returns the result immediately after that line of code, which is triggered once the first overlapping element is found (ie our answer will only have one element). If we put it at the end of the function instead, it will only return once the algorithm is complete.
I also moved the definition of mylist
inside the function, otherwise you'd be overwriting your results if you call the function multiple times.
Also, since you're learning python, I also might look into list comprehensions, which are considered more "pythonic", are more concise, and in many cases execute faster:
def intersection(lst1, lst2):
return [n for n in lst1 for o in lst2 if n == o]
However, both of the above implementations will have duplicates in the result of an overlapping element appears more than once in either list. For example:
intersection([1,1,2,3], [1,1,2,4])
>>> [1,1,1,1,2]
A better implementation would use python sets and the built in set intersection operator:
def intersection(lst1, lst2):
return list(set(lst1) & set(lst2))
intersection([1,1,2,3], [1,1,2,4])
>>> [1,2]