How to Check the Length of an Array in Python?

As a data scientist working for a US-based company, I recently faced a problem where I needed to find the length of an array in Python. After researching and experimenting with different methods, I discovered several ways to accomplish this task efficiently. In this article, I will share my findings and provide examples with screenshots of executed example code.

Arrays in Python

Before we check the length of an array, it’s essential to understand what is Python array. Python doesn’t have a built-in array data type. Instead, it uses lists and the numpy library to create and manipulate arrays.

Lists in Python

Python lists are one of the most commonly used data structures in Python. They can hold a collection of items, which can be of different types. Here’s a simple example of a list in Python:

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]

Read How to Create a 2D Array in Python

Arrays with Numpy in Python

For more advanced operations, Python developers often use the NumPy library, which provides support for arrays. Here’s how you can create an array using NumPy:

import numpy as np

temperatures = np.array([32, 45, 50, 60, 72])

Check out How to Print an Array in Python

Check the Length of an Array in Python

Now that we have a basic understanding of arrays and lists in Python, let’s explore the different methods to check their length.

1. Use the len() Function

The easiest way to find the length of a list or an array in Python is by using the len() function. This built-in function returns the number of elements in the list or array.

Example with a List

Consider the following list of cities:

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]

To find the length of this list, you simply use the len() Function:

length_of_cities = len(cities)
print(f"The number of cities is: {length_of_cities}")

Output:

The number of cities is: 5

I executed the above example code and added its screenshot below.

Check the Length of an Array in Python

Example with a Numpy Array in Python

For a NumPy array, the process is similar. Here’s an example:

import numpy as np

temperatures = np.array([32, 45, 50, 60, 72])
length_of_temperatures = len(temperatures)
print(f"The number of temperature readings is: {length_of_temperatures}")

Output:

The number of temperature readings is: 5

Read How to Initialize a 2D Array in Python

2. Use the size Attribute in Python Numpy

When working with Python NumPy arrays, another useful attribute is size, which directly gives the number of elements in the array. Here’s how you can use it:

import numpy as np

temperatures = np.array([32, 45, 50, 60, 72])
length_of_temperatures = temperatures.size
print(f"The number of temperature readings is: {length_of_temperatures}")

Output:

The number of temperature readings is: 5

I executed the above example code and added its screenshot below.

How to Check the Length of an Array in Python

Check out ValueError: Can Only Convert an Array of Size 1 to a Python Scalar [How to Fix]

3. Use the len() Method

Python objects have a special method called __len__(), which is internally called by the len() function. You can use this method directly, though it’s less common than using len().

Example with a List

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
length_of_cities = cities.__len__()
print(f"The number of cities is: {length_of_cities}")

Output:

The number of cities is: 5

I executed the above example code and added its screenshot below.

Check the Length of an Array in Python Use the len() Method

Example with a Numpy Array in Python

import numpy as np

temperatures = np.array([32, 45, 50, 60, 72])
length_of_temperatures = temperatures.__len__()
print(f"The number of temperature readings is: {length_of_temperatures}")

Output:

The number of temperature readings is: 5

Read How to Create an Array from 1 to N in Python

Applications of Check the Length of a Python Array

How to check the length of an array is essential in various real-world applications. Here are a few scenarios where this knowledge is particularly useful:

Data Analysis

When analyzing data, you often need to know the size of your dataset. For example, if you are working with a dataset of temperatures recorded in different cities across the USA.

import numpy as np

temperature_readings = np.array([32, 45, 50, 60, 72, 55, 63, 70, 75, 80])
num_readings = len(temperature_readings)
print(f"Total number of temperature readings: {num_readings}")

Web Development

In web development, you might need to display a list of items, such as user comments or product reviews.

comments = ["Great product!", "Very satisfied.", "Could be better.", "Excellent service.", "Not worth the price."]
num_comments = len(comments)
print(f"Total number of comments: {num_comments}")

Machine Learning

In machine learning, datasets are often split into training and testing sets. Knowing the length of your arrays helps ensure that you correctly partition your data.

import numpy as np

data = np.array([i for i in range(100)])  # Example dataset
train_size = int(0.8 * len(data))
test_size = len(data) - train_size

train_data = data[:train_size]
test_data = data[train_size:]

print(f"Training data size: {len(train_data)}")
print(f"Testing data size: {len(test_data)}")

Check out How to Write an Array to a File in Python

Conclusion

In this tutorial, I explained how to check the length of an array in Python using various methods. Whether you are working with lists or NumPy arrays, the len() function is best for quickly determining the number of elements. Additionally, NumPy’s size attribute and the __len__() method offer alternative ways to achieve the same result. I also discussed real-time applications to check the length of a Python array in the field of Data Analysis, Web Development and Machine Learning.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.