8

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.

13
  • 1
    of course, so why does the first one pass? Commented Aug 1, 2022 at 8:47
  • 4
    It's an optimization: first check is reference equality (roughly similar to id(lst[0]) == id([lst[0])), if that fails an elementwise check is performed. That fails for lst[0] == lst[1] if those are numpy arrays. Commented Aug 1, 2022 at 8:56
  • 1
    @o17tH1H'S'k - I'd rather find the dupe. It's hard to search, but this has been answered before. Commented Aug 1, 2022 at 9:06
  • 1
    Sorry, but Guarantees that identity implies equality is what a buggy logic... l = [inf, nan]; i = float("inf"); n = float("nan"); print(l.index(i), 'Works'); print(l.index(nan), 'Works'); print(l.index(n), 'Fails') Commented Aug 1, 2022 at 9:17
  • 1
    @MichaelSzczesny, I meant from numpy import nan, inf Commented Aug 1, 2022 at 9:42

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.