index of an numpy array in a list

Viewed 216

Trying to index or remove a numpy array item from a python list, does not fail as expected on first item.

import numpy as np

# works:
lst = [np.array([1,2]), np.array([3,4])]
lst.index(lst[0])

# fails with: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
lst = [np.array([1,2]), np.array([3,4])]
lst.index(lst[1])

I understand why the second fails, I would like to understand why the first one works.

1 Answers

Because it's not leveraging the array's eq method, but rather just comparing the ids of the two objects:

lst = [np.array([1,2]), np.array([3,4])]
lst[0]                                  => array([1, 2])
lst[1]                                  => array([3, 4])
lst[0] == lst[1]                        => array([False, False], dtype=bool)
id(lst[0])                              => 140232956554776
id(lst[1])                              => 140232956554960
lst.index(lst[0])                       => 0
lst.index(lst[1])                       => 1
lst.index(lst[0]) == lst.index(lst[1])  => False

To get the behavior you want, you need to make a comparison that leverages the array's eq, such as:

lst.index(lst[0].tolist()) => 0
lst.index(lst[1].tolist()) => 1

Or:

lst.index(lst[0].tostring()) => 0
lst.index(lst[1].tostring()) => 1

But this is not going to be an efficient way to work with the data, since you'll be converting the arrays to lists or strings.

Related