OKPEDIA PYTHON VECTOR

How to count elements of an array in Python

To count the elements of an array in Python, use the size method of the numpy module

x.size

The object x is an array, matrix or vector, created using numpy's array () function.

The size method returns the length of array.

Note. The size method can also be called as a size(x) function by specifying the array object in parentheses.

Example

Example 1

Create a 3-row, 3-column array using numpy's array() function.

>>> from numpy import array
>>> matrix=array([[0,0,0],[0,0,0],[0,0,0]])

Count the elements of the array with the size method

>>> matrix.size

The size method returns the number of elements as output

9

The matrix has nine elements.

Example 2

The same result is obtained using size function

>>> from numpy import size
>>> size(matrix)

The function calculates the length of the array

9

The matrix has nine elements.

https://how.okpedia.org/en/python/how-to-count-elements-of-an-array-in-python


Report an error or share a suggestion to enhance this page


Python


FacebookTwitterLinkedinLinkedin