How to Find the Length of an Array in Python?

In Python, you can find the length of an array using various methods. The most commonly used method is the built-in len function, which returns the number of elements in an array.

Here’s an example of how to use len to find the length of an array:

Using the len() Function

The len function is the most direct and commonly used method to find the number of elements in a list or any iterable. It is a built-in Python function that applies to a wide range of iterable collections.

See also  Natural Language Processing with Python: An Introduction

my_array = [1, 2, 3, 4, 5]
length = len(my_array)
print(length) # Output: 5

len(my_array) returns 5, indicating the number of items in the list.

Using NumPy’s shape Attribute

Another way to find the length of an array is by using the shape attribute of an array from the NumPy library. Here’s an example of how to use NumPy to find the length of an array:

See also  3D Data Visualizations in Python with Mayavi

import numpy as np

my_array = np.array([1, 2, 3, 4, 5])
length = my_array.shape[0]
print(length) # Output: 5

In this example, after importing the NumPy library, we create an array with the array method. The shape attribute is then utilized to determine the array’s length, specifically its first dimension.

Both methods are valid ways to find the length of an array in Python. It’s up to you to choose the method that best fits your needs and the requirements of your program.

Using the len Function with Multi-dimensional Arrays

For multi-dimensional arrays, len returns the size of the first dimension, illustrating its limitation in handling arrays beyond one dimension.

multi_array = np.array([[1, 2, 3], [4, 5, 6]])
length = len(multi_array)
print(length) # Output: 2 (number of rows)

len(multi_array) returns 2, which is the size of the first dimension (number of rows).