Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude items from list of lists Python

Tags:

python

list

I have the next list of

testList = []

testList.append([0,-10])
testList.append([-12,122])
testList.append([13,172])
testList.append([17,296])
testList.append([-10,80])
testList.append([-16,230])
testList.append([-18, 296])
testList.append([-2, -8])
testList.append([-5,10])
testList.append([2,-4])

and another lists which contains elements from previous list:

m1 = []
m1.append([0, -10])
m1.append([13, 172])

Then I try to get a subarray from the list testList with the next statement:

[element for i, element in enumerate(testList) if i not in m1]

But I get the same list as testList.

How can I achieve this?

like image 842
Chema Sarmiento Avatar asked Nov 07 '15 00:11

Chema Sarmiento


3 Answers

If you don't care about the order in the lists, you can use sets instead:

# result will be a set, not a list
not_in_testlist = set(testlist) - set(m1) 

If you want the result to be a list again:

 # result will be a list with a new order
not_in_m1 = list(set(testlist) - set(m1))

Be aware that using sets will lose the order of the original lists because sets are unordered types (they use hashing under the hood).

If you need to preserve the order, then Andrew Allaire's answer is correct:

# result is a list, order is preserved
not_in_testlist = [e for e in testlist if e not in m1] 
like image 170
skrrgwasme Avatar answered Oct 19 '22 04:10

skrrgwasme


The problem is with your use of enumerate. The i is just going to be an integer, and therefor never in a list that only has lists in it. Try this:

[element for element in testList if element not in m1]
like image 35
Andrew Allaire Avatar answered Oct 19 '22 06:10

Andrew Allaire


Try with this:

def clean_list(my_list, exclusion_list):

    new_list = []
    for i in my_list:
        if i in exclusion_list:
            continue
        else:
            new_list.append(i)

    return new_list
like image 4
David Avatar answered Oct 19 '22 06:10

David