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
Changing a list as you iterate over it will cause problems. Your second solution is decent, or you can check out "list comprehensions". In this case:
new_list = [num for num in list1 if num not in list2]
Impress your professor by cheating:
def subtract_list(l1, l2):
return list(sorted(set(l1) - set(l2)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With