An array is not a built-in data type in Python, but we can create arrays using third-party libraries. By length of an array, we mean the total number of elements or items in the given array. In order to calculate the length of an array, we can use various methods discussed below in this blog.
Table of contents
- Length of array
- Finding the length of an array using the len() function
- Using Numpy to find the length of an array in Python
- Closing thoughts
Length of array
In Python, an array is a collection of items stored at contiguous memory locations. It is a special variable, which can hold more than one value with the same data type at a time. We know array index starts from 0 instead of 1, therefore the length of an array is one more than the highest index value of the given array.
Finding the length of an array using the len() function
To find the length of an array in Python, we can use the len() function. It is a built-in Python method that takes an array as an argument and returns the number of elements in the array. The len() function returns the size of an array.
Syntax:
len (name_of_the_array)
Input:
arr = [0, 1, 2, a, 4]
print ("The given array is: ")
print (arr)
# Finding length of the given array
size = len(arr)
print ("The length of array is: ")
print (size)
Output:
The given array is:
[0, 1, 2, a, 4]
The length of array is:
5
Using Numpy to find the length of an array in Python
Another method to find the length of an array is Numpy "size". Numpy has a size attribute. The size is a built-in attribute that returns the size of the array.
Syntax:
name_of_the_array.size
Input:
import numpy as np
arr = np.array([0, 1, 2, a, 4])
print ("The given array is: ")
print (arr)
# Finding length of the given array
size = arr.size
print ("The length of array is: ")
print (size)
Output:
The given array is:
[0, 1, 2, a, 4]
The length of array is:
5
Closing thoughts
Unlike other programming languages like JavaScript, PHP or C++, Python does not support "length()" or "size()" functions to find the length of an array. The len() function takes the array as a parameter and returns the size. One can read more about other Python concepts here.
Top comments (0)