1

According to Numpy's argmax documentation, the first argument we pass to np.argmax must be an array.

If the array is an empty list, we get a ValueError Exception:

import numpy as np
print(np.argmax([]))

ValueError: attempt to get argmax of an empty sequence

However, if we pass None as the first argument to np.argmax, we get 0 as the output.

import numpy as np
print(np.argmax(None))

0

I find it odd that when it is passed an array (albeit empty but an array nonetheless) to np.argmax we get an Exception but when it is passed NOT an array (None) the program runs without error.


My questions:

  1. Why does it not return an Exception since None is not an array?
  2. Why does it return 0?
ihavenoidea
  • 629
  • 1
  • 7
  • 26

1 Answers1

2

The input of numpy.argmax is not required to be an array - you're misreading the docs. The input is an array-like, which turns out to barely constrain the input at all. Almost anything is an array-like, including None, which is considered a 0-dimensional array-like of object dtype. Rather than constraining the input, "array-like" really describes how the input will be interpreted - if a parameter is documented as an array-like, NumPy will try to treat it as an array, usually with the equivalent of an asarray call.

If you don't pass an axis, argmax treats the input as flattened, so your call is equivalent to numpy.argmax(numpy.array([None])). None isn't comparable, but numpy doesn't know that, because it has nothing to compare None to - there's only one input element, and that one input element is considered the max by default. argmax returns 0, the index of the only element in the flattened input.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • I was not aware of the "array-like" definition, thanks! Can you expand (or post a source) on this statement ``...which is considered a 0-dimensional array-like of object dtype``? I would like to read more about it. – ihavenoidea Apr 04 '21 at 22:57
  • 1
    @ihavenoidea: Try calling `asarray` on `None`, and you'll get a 0-dimensional array with `object` dtype. – user2357112 Apr 05 '21 at 02:09