up vote 2 down vote favorite
share [g+] share [fb]

If I have a list of numpy arrays, then using remove method returns a value error.

For example:

import numpy as np

list = [np.array([1,1,1]),np.array([2,2,2]),np.array([3,3,3])]

list.remove(np.array([2,2,2]))

Would give me

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I can't seem to get the all() to work, is it just not possible?

link|improve this question
Just so you know, it isn't a good idea to use list as a variable since it is a keyword in Python. It can come back to bite you later on. – Justin Peel Jul 1 '10 at 17:40
Yes thanks, I was bitten whilst playing around trying to solve this problem, converting the arrays to lists using list() then using remove and so on. – matt_s Jul 2 '10 at 10:24
feedback

2 Answers

The problem here is that when two numpy arrays are compared with ==, as in the remove() and index() methods, a numpy array of boolean values (the element by element comparisons) is returned which is interpretted as being ambiguous. A good way to compare two numpy arrays for equality is to use numpy's array_equal() function.

Since the remove() method of lists doesn't have a key argument (like sort() does), I think that you need to make your own function to do this. Here's one that I made:

def removearray(L,arr):
    ind = 0
    size = len(L)
    while ind != size and not np.array_equal(L[ind],arr):
        ind += 1
    if ind != size:
        L.pop(ind)
    else:
        raise ValueError('array not found in list.')

If you need it to be faster then you could Cython-ize it.

link|improve this answer
Thank you, very useful! – matt_s Jul 2 '10 at 9:50
feedback

Here you go:

list.pop(1)

Update:

list.pop(list.index(element))

I don't think you can get around traversing the list to find the position of the element. Don't worry about it. Python will, by default use a good searching algorithm to find it at least cost for you.

link|improve this answer
Thanks, I realise that works for my example but where I actually need to do this I don't know the position of the array I want to remove. Rather than using a loop I thought there might be a nicer way using the remove method. – matt_s Jul 1 '10 at 12:49
Thanks for helping me with this. If I use list.index() for a numpy array I get the ambiguous truth error again, hmm. – matt_s Jul 1 '10 at 13:11
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.