How to Find the Array Length in Python

To find the length of an array in Python, you can use the built-in “len()” function. For example, len([11, 21, 19, “k”, 46]) returns 5. The len() method takes an argument where you can provide an array and returns the length of the given array.

Syntax

size = len(arr)

Parameters

The len() method takes a required parameter, an array, or a list.

Example: How to Use len() function in Python

numbers = [11, 21, 19, 18, 46]

print("The size of an array is: ", len(numbers))

Output

The size of an array is: 5

Finding the size of an array in Python

To find the size of an array, use the built-in numpy size property. The numpy array has size and shape attributes, but the size and shape attributes are not quite the same.

import numpy as np

arr = np.array([[1, 2], [3, 4], [5, 6]])

print("The size of a numpy array is: ", arr.size)

Output

The size of a numpy array is: 6

The size property works great with one-dimensional arrays. It does not consider the multi-dimensional arrays; it only gives us the number of elements in an array.

Conclusion

The best way to find an array length in Python is to use the len() function, which takes the array as a parameter and returns its length.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.