Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list subtraction [duplicate]

Tags:

python

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 from list1 that can be found in list2.

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
like image 527
Jasko Avatar asked Jun 20 '14 13:06

Jasko


2 Answers

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]
like image 158
thumbtackthief Avatar answered Sep 24 '22 10:09

thumbtackthief


Impress your professor by cheating:

def subtract_list(l1, l2):
    return list(sorted(set(l1) - set(l2)))
like image 23
jaime Avatar answered Sep 22 '22 10:09

jaime