What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

How to Find Length of an Array in Python? (5 Best Methods)

  • Sep 19, 2022
  • 6 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Mradula Mittal
How to Find Length of an Array in Python? (5 Best Methods)

When working with data, it is inevitable to struggle in data organization. As a result, data structures come into play. They make it easier to organize, store and perform data operations. An array is one of the most fundamental data structures. Let's take a deeper look at Arrays before moving on to determining their length.

What is an Array?

Arrays are linear data structures that store similar data (elements of the same data type) contiguously. In other programming languages, generally, arrays have a fixed (pre-defined) size. Even when altered, the length of an array is important for performing many operations.

A logical view of an array

Let's look at an array to find the difference between index and length:

logical view of a an array

Consider the above array to be of length n. Then the indexing will begin from 0 to n-1.

Hence, the last index of an array = length of array - 1

In Python, an array is not an in-built data type. Python has Lists instead of Arrays.

Lists are similar to Arrays, yet not the same. There are a lot more differences between Python and Lists.

Difference between List and Array

An array can only store similar data, i.e. data of the same data type, whereas a list can store elements of various data types.
For example-:
Consider an array of numbers (integers)
a = [1, 2, 3, 4, 5]
For array a = [1, 'a', 2, 'ab'] -> is invalid
However, in the case of lists in Python, 
b = [1, 2, 3, 4 ] and b = [1, 'a', 2, 'ab'] both are valid.

Generally, an array has a fixed size while Lists in Python have dynamic memory space. We can always append (add) or remove elements from a list to change its length, while an array length can not be altered once defined (Again in most languages!).

Declare Arrays in Python Using an Array Module

Although Python provides a better alternative to Arrays (Lists), there are some cases where Arrays are preferred. Python includes an Array Module that allows you to declare and use arrays. Before we get into how to find the length of an array in Python, let's go over how to declare Arrays in Python using the Array Module.

import array as arr

 

To begin working with "Arrays" in Python, you must first import the array module. To shorten your reference to the module, you can always use 'as'. Remember that the use of 'as' is optional.

Initializing an array using the Array module

Array objects are used to initialize or declare arrays. It will be more clear through the following code-

#import the array module
import array as arr

#declaring an array using array object
array1 = arr.array('i', [1,2,3,6])
# 'i' stands for signed integer
print(array1)

 

We need to define the data type while declaring an array, since an array stores only similar values. There are many other data types with different symbols to represent them while declaring an array.

Output:

array('i', [1, 2, 3, 6])

 

Learn more about initializing an array in python.

When we print an array and a list, you'll notice the difference. The array displayed above also includes the data type, whereas a list does not.

Do you know that you can always create an array using a list? Well, that's pretty simple to do. Giving you a hint below:

a = [1,2,5,3,4]
array1 = arr.array('i', a)

 

Remember to import the array module. The code above also makes the difference between a list and an array clear. 

How to Find Length of an Array in Python?

What do you understand by the length of an array?

The length of an array can be described as an array's capacity to hold data elements, of the same data type. There are many operations that require the length of an array. Python provides numerous methods for determining the length of an array, a few of them are listed below-

Method 1: Using len() method

The most common practice is using a List as an Array. The len() method is an in-built method that returns the length of the list.

Syntax: 

len(arrayName)

Using len() method on the List:

#Find length of an Array in Python
#Declare an array (list)
arr = [10, 20, 30, 40, 50]
#using len() function
lengthOfArray = len(arr)
print("The length of ", arr, ' is : ', lengthOfArray)
#You can directly use len(arr) instead of lengthOfArray

 

Output: 

The length of  [10, 20, 30, 40, 50]  is :  5

 

The above code works for lists used as an array. We can also use the array Module to create an array and then use the len() method to determine its length. Check the code below for finding the length of an array using Array Module:

Using len() method on Array

#import the array module
import array as arr

a = arr.array('i', [10, 20, 30, 40, 50])
print("The length of array is: ", len(a))

 

Output:

The length of array is:  5

 

Method 2: Using For Loop (The Naive Method Part 1)

This is the most basic method for determining the length of an array in Python. The only thing needed is to run a for loop on the array and record the increment in a variable. Take a look at the below code to get a better idea-

Using for Loop in a List

Let's first try out finding the length of a list using the for a loop. Note that the variable 'length' is initialized to 0. Its value increases as the loop go through each element of the array (list).

#Find length of a List in Python
#Create a List
a = [10, 20, 30, 40, 50]

#create a variable to hold the length
length = 0
for element in a:
    length += 1
print("The length of the array", a, " is: ", length)   

 

Output: 

The length of the array [10, 20, 30, 40, 50]  is:  5

 

Using a for Loop on an Array

#Find the length of a List in Python
#Create an array
import array

a = array.array('i', [1, 2, 3, 8, 9])

#create a variable to hold the length
length = 0
for element in a:
    length += 1
print("The length of the array", a, " is: ", length)

 

Output:

The length of the array array('i', [1, 2, 3, 8, 9])  is:  5

 

 I've posted the code for both, an array as well as a List, so that any Python user can find it easy to work with as a beginner!

Method 3: Using __len__() method

Although sounds (read) similar, len() and __len__() method are quite different in their functionality. __len__() method is also an in-built method in Python. Actually, when we call for len() method, it internally calls the __len__ () method to do the job. Note that len() only works for iterables.

Though len() and __len__(), both return the length of the array in Python, there is a slight difference in their syntax. While we pass on the object as an argument to len() method, we call for __len__() method using the object (list), just as:

Syntax: 

arrayName.__len__()

 

For example: 

#Find length of a List in Python
import array

#Creating an array 
a = array.array('i', [1, 2, 3, 8, 9])

#calling the __len__() method
length = a.__len__()

print("The length of the array", a, " is: ", length)
  

 

Output:

The length of the array array('i', [1, 2, 3, 8, 9])  is:  5

 

Method 4: Using length_hint() method

Python includes an 'operator' module with functions that are equivalent to Python's intrinsic operators. This module is useful when we want to pass callable methods as an argument to another Python object. The length hint() method is an in-built method in the Operator Module. It returns an estimate of how many elements an object contains. 

Example: 

#Find length of a List in Python
import array
#import the length_hint() method from operator module
from operator import length_hint

#Create an array 
a = array.array('i', [1, 2, 3, 8, 9])

#Create a List
b = ['a', 'b', 'c', 'd']

#Calling the length_hint() method
print('The length of array ', a, ' is: ', length_hint(a))
print('The length of list ', b, ' is: ', length_hint(b))

 

It should be noted that the length hint() method returns an estimate of an array's storage capacity. When applied to an object that supports the len() method, it yields the same result as len() (). In the case of other objects, however, it may return an undervalued or overvalued length.

Output: 

The length of array  array('i', [1, 2, 3, 8, 9])  is:  5
The length of list  ['a', 'b', 'c', 'd']  is:  4

 

Before jumping off to the next method, let's take a quick look at 1-D and 2-D arrays:

1D and 2D arrays

Method 5: Using NumPy library

For budding data scientists, Numpy is an important library. The above-mentioned methods work fine with 1-Dimensional arrays, but in the case of 2-Dimensional arrays, they don't exactly return the total number of elements. 

Have a look at the below code: 

#Find length of a List in Python
from operator import length_hint
#Create a 2-Dimensional List
b = [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']]

print ('The length of list ', b, ' is: ', len (b))
print ('The length of list ', b, ' is: ', b.__len__())
print ('The length of list ', b, ' is: ', length_hint(b))

 

Output: 

The length of list  [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']]  is:  2
The length of list  [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']]  is:  2
The length of list  [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']]  is:  2

 

You see! The total number of elements is actually 8, while the result displays 2.

To overcome this shortcoming, NumPy includes built-in methods for determining the total length of an array. Before we get there, let's look at how to find the length of an array (1-D) in Python using the Numpy library.

Use of  .size

Numpy array offers 'size' attribute that, as the name states, returns the size of a numpy array. It is not affected by the dimensionality of an array. It returns the total number of elements in that array.

#Find length of a List in Python
#import numpy
import numpy as np

#creating a numpy array
a = np.array([10, 56, 7, 8, 49, 100, 78])
b = np.array([[1,2,3], [10, 20 , 30]])
#Printing length of the 1-D array
print("The length of ", a , ' is: ', a.size)
#Printing length of the 2-D array
print("The length of ")
print(b , ' is: ', b.size)

 

Output:

The length of  [ 10  56   7   8  49 100  78]  is:  7
The length of 
[[ 1  2  3]
 [10 20 30]]  is:  6

 

Use of .shape

Numpy also has a 'shape' attribute that can be used to determine the size of an array. Rather than returning the total number of elements in an array, this attribute returns a tuple containing the array's rows and columns, in the form (rows, columns)

Example- 

#Find length of a List in Python
#import numpy
import numpy as np

#creating a numpy array
a = np.array([10, 56, 7, 8, 49, 100, 78])
b = np.array([[1,2,3], [10, 20 , 30]])
#Printing length of the 1-D array
print("The length of ", a , ' is: ', a.shape)
#Printing length of the 2-D array
print("The length of ")
print(b , ' is: ', b.shape)

 

Output:

The length of  [ 10  56   7   8  49 100  78]  is:  (7,)
The length of 
[[ 1  2  3]
 [10 20 30]]  is:  (2, 3)

 

Note how the result for 1-D arrays shows nothing in place of columns since it has 0 columns.

Conclusion

When we need to access the array elements using their index or pass on the array size, the length of an array is extremely useful. The methods described above are among the simplest in Python for determining the length of an array or list. Despite the fact that they both produce the same output, their time complexity differs. You should use a method that is compatible with your code.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Mradula Mittal
I'm Mradula Mittal, a tech community enthusiast with a knack for content writing. Always eager to learn more about Python and Machine Learning. Having an analytical brain, I'm particular about my research and writing. I live by the motto "the more you share, the more you learn" and being a techie, it's fun to learn, create and share.