DEV Community

hrishikesh1990
hrishikesh1990

Posted on • Originally published at flexiple.com

How to calculate the length of an array in Python?

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

  1. Length of array
  2. Finding the length of an array using the len() function
  3. Using Numpy to find the length of an array in Python
  4. 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)
Enter fullscreen mode Exit fullscreen mode

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) 
Enter fullscreen mode Exit fullscreen mode

Output:

The given array is: 
[0, 1, 2, a, 4]
The length of array is: 
5
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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) 
Enter fullscreen mode Exit fullscreen mode

Output:

The given array is: 
[0, 1, 2, a, 4]
The length of array is: 
5
Enter fullscreen mode Exit fullscreen mode

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)