Quick way to access first element in Numpy array with arbitrary number of dimensions?

a.flat[0]

This should be pretty fast and never require a copy. (Note that a.flat is an instance of numpy.flatiter, not an array.)


You can use a.item(0); see the documentation at numpy.ndarray.item.

A possible disadvantage of this approach is that the return value is a Python data type, not a numpy object. For example, if a has data type numpy.uint8, a.item(0) will be a Python integer. If that is a problem, a.flat[0] is better--see @user2357112's answer.

Tags:

Python

Numpy