How to find out the length of a Python array

If you work with arrays in Python and want to find out their length, you have several options to choose from. Here, we’ll explain how to use the Python functions len and size.

How to find out a Python array length using len

Python only supports Python lists. To use arrays, you need to import other libraries first. Integrating NumPy into your project will allow you to use Python arrays. To find out the number of elements in your array, you can use the native Python len function.

In the following example, we’ll create an array that contains the numbers 0 to 5. Using len ensures that the length of our Python array will be assigned to the variable l.

import numpy as np
a = np.array([0,1,2,3,4,5])
l = len(a)
python

Since the array has a total of six elements, the value 6 is now saved in the variable l.

The len function can also be used to find the length of Python lists. These are used by many programmers as a sort of array replacement in the event that no additional libraries should be used in a project.

Tip

Using Python for your web project? To deploy changes to your project in real time, you can use Deploy Now by IONOS. The direct connection to GitHub makes your workflows easier and ensures that you always have an overview of your project’s status.

How to find out a Python array length using size

If you work with NumPy, the library also has a way to find out Python array length. It’s called size and is defined only for arrays, meaning if you want to use it for Python lists, it won’t work. Unlike with len, when you use size, you can also find out the number of elements in a multidimensional array.

To give you a better idea of how to use size, we’ll give you a code example. First, we’ll create the same array as in the example above, which contains the numbers 0 to 5 and saves the variable l as length. Then, we’ll create an array that is made up of three unique arrays and save this with the variable s.

import numpy as np
# onedimensional Array
a = np.array([0,1,2,3,4,5])
l = a.size
# multidimensional Array
m = np.array([[0,1,2], [3,4,5], [6,7,8], [9,10,11]])
s = m.size
python

When you look at the l variable, you can see that there is no difference to len. This is because, in this case, the variable l contains six elements.

However, there is a surprise with size. With the m variable, we find the number 12. This is because size counts the elements of all arrays individually. If you used len here, it would return the number 4, since len only refers to the first dimension of the array, which in the example above is divided into four sub-arrays. The elements that len counts are “[0,1,2]”, “[3,4,5]”, “[6,7,8]” and “[9,10,11]”.

We use cookies on our website to provide you with the best possible user experience. By continuing to use our website or services, you agree to their use. More Information.