7

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?

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Chema Sarmiento
  • 279
  • 2
  • 3
  • 11

3 Answers3

18

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] 
skrrgwasme
  • 9,358
  • 11
  • 54
  • 84
9

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]
Andrew Allaire
  • 1,162
  • 1
  • 11
  • 19
  • Using Sets as skrrgwasme suggested are far more efficient because they use hashing under hood. However you would need your elements to be tuples and not lists, since lists are not hashable (I would comment on his answer, but I lack the reputation to do so). – Andrew Allaire Nov 07 '15 at 01:37
4

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
skrrgwasme
  • 9,358
  • 11
  • 54
  • 84
David
  • 41
  • 2
  • This should work, but it's unnecessarily verbose. This type of manipulation is what [list comprehensions](http://www.secnetix.de/olli/Python/list_comprehensions.hawk) are made for. – skrrgwasme Nov 07 '15 at 01:08