This is the practice example :
Write a function
(list1, list2)
that takes in two lists as arguments and return a list that is the result of removing elements fromlist1
that can be found inlist2
.
Why does this function return [1, 3, 4]
and not [4]
as I thought it would? I think it has something to do with list1.remove()
. I guess it's something obvious, but I can't see it.
It works on these examples:
subtractList (['a', 'b', 'c', 'd'], ['x', 'y', 'z']) =
['a', 'b', 'c', 'd']
subtractList([1,2,3,4,5], [2, 4]) =
[1, 3, 5]
but fails on this:
subtractList(range(5), range(4))
Also i noticed it removes only even numbers from the list.
Here is the code:
def subtractList(list1,list2):
list1 = list(list1)
list2 = list(list2)
for i in list1:
if i in list2:
list1.remove(i)
return list1
I have solved this practice with:
def subtractList(list1,list2):
new_list = []
list1 = list(list1)
list2 = list(list2)
for i in list1:
if i not in list2:
new_list.append(i)
return new_list