Arrays make it easy to group values in Python. Keeping these values in one place makes them easy to reference and access at a later point in your code. Arrays thus pave the way for streamlined, manageable code.

This article looks at the different types of arrays in Python and the benefits of each. We’ll then explain how to calculate the length of an array in Python and how we can use array length to alter control flow and determine how much memory an array uses.

What Is an Array?

An array in Python is a group of data points in consecutive memory locations. It’s a special type of variable that contains multiple values that must all be of the same data type. Programmers use arrays to store groups of number values efficiently in code.

Building an Array in Python

There are different ways to build an array in Python. Below we’ll go over lists, arrays, and NumPy arrays.

Lists

What you might know as an array in another language like C++ or  Java is actually a list in Python. While it is easy to confuse lists with arrays in Python, a single list can include any number of data types. Lists also do not require the use of a module and can incorporate strings that arrays cannot:

planets = ["Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune"]
data = [3, 4.5, 10, 20, 50]

Lists are a convenient way of capturing similar data in one place within code.  But Python gives you the ability to create arrays as well.  

The Array Module

Python has a module dedicated to arrays in its standard library. The module is conveniently named array, and you’ll have to import it to use it. The syntax for adding the array module to your program looks like this:

import array

With the array module imported, you can use this syntax to add an array into your code:

array.array(data type, list of values)

You’re required to list a specific data type for your array upon declaration. All of the array’s values must be of that same data type or your program will return an error. Python uses a series of type codes to identify an array’s data type.

For example, type code ‘i’ is not signed integers, while ‘f’ is for float. See the full list at this Python documentation page.

Your list of values can be any length, from one to theoretical infinity. Below are some examples of arrays you might find in Python:

import array
counts = array.array('i', [10, 20, 30, 40, 50, 60, 70, 80])
amounts = array.array('f', [4.56, 10.00, 3.78, 56.80])

The NumPy Module

NumPy, or Numerical Python, is a Python module that creates arrays out of lists. This gives NumPy the benefit of using less memory as an array, while being flexible enough to accommodate multiple data types. NumPy also lets programmers perform mathematical calculations that are not possible with standard arrays.

While the array module is one of Python’s core libraries, the NumPy module is not. You’ll need to install NumPy using the pip3 install numpy command to use it.

Declaring a NumPy array is not much different from declaring a standard array in Python, except there’s no need to list a data type:

import numpy

random = numpy.array([1, 2.5, 4, "tree"])

Now that we have an understanding of how to create Python’s various arrays, we’ll need to look at the significance of array length.

Using Lists and Arrays in Python

Both lists and arrays help keep code organized by keeping groups of data together in one place. This makes code easier to read and keeps your data concise. Let’s look at each and see when they are most beneficial to use:

Benefits of Lists

While lists are bulkier to store, they allow the convenience of not having to call upon a module and are not limited to one data type. When you have a shorter sequence of values, lists can be the best choice.

Benefits of Arrays

Arrays store each value in subsequent memory locations. Each value in an array is of a specific data type. The program thus knows how much memory to set aside for each. Values in an array tend to be only 2 to 4 bytes versus 64 bytes for each value in a list. This makes arrays much more energy efficient than a list.

Benefits of NumPy Arrays

NumPy is a popular module that is the standard library for scientific computing. NumPy arrays are more compact than lists but also allows for multiple data types in a single array. You can use NumPy for more complex operations such as matrix multiplication. Most deep learning and machine learning libraries build on top of NumPy as well.

How To Calculate the Length of an Array in Python

The length of an array represents the number of elements it contains. When using a list or NumPy array consisting of a string, the length reveals the number of characters in that string. Let’s look at how to calculate array length and ways to use it in your code.

Python makes it easy to calculate the length of any list or array, thanks to the len() method. len() requires only the name of the list or array as an argument. Here’s how the len() method looks in code:

import array

counts = array.array('i', [10, 20, 30, 40, 50, 60, 70, 80])
counts_length = len(counts)
print(counts_length)

It should come as no surprise that this program outputs 8 as the value for counts_length.

You can use the len() method for NumPy arrays, but NumPy also has the built-in typecode .size that you can use to calculate length.

import numpy

counts = numpy.array([10, 20, 30, 40, 50, 60, 70, 80])

print(len(counts))

print(counts.size)

Both outputs return 8, the number of elements in the array.

NumPy is unique in allowing you to capture multi-dimensional arrays. Calling size() on a multi-dimensional array will print out the length of each dimension.

Array Length Use Cases

Array length serves to alter control flow and determine how much memory an array uses.

Altering Control Flow

You can use array length in code to alter control flow. This simple example shows just one potential use for a length value:

import numpy

counts = numpy.array([10, 20, 30, 40, 50, 60, 70, 80])
if len(counts) > 5:
    print("This array meets the minimum length requirement.")
else:
    print("This array is too short!")

Luckily, our array of 8 values meets the minimum length requirement.

Determining How Much Memory an Array Uses

You could also use array length in conjunction with NumPy’s itemsize attribute to tell you the total number of bytes the array uses in memory. Here’s an example of what this looks like:

import numpy

counts = numpy.array([10, 20, 30, 40, 50, 60, 70, 80])
memory_in_bytes = counts.itemsize * len(counts)
print("This array uses", memory_in_bytes, "bytes.")

Each integer uses 4 bytes of data for a total of 32 bytes in memory.

Calculating Lengths of Strings

Using len() with a list that makes up a string will reveal the number of characters that make up the string. Strings, just like lists, are a collection of items. Therefore, a string’s length is equal to the number of characters within. Take a look at how this works:

phrase = "Hello, World!"
print("This phrase contains", len(phrase), "characters.")

We get the following output:

This phrase contains 13 characters.

Learn Python at Home With Udacity

This article explored lists, arrays, and NumPy arrays in Python and the benefits of each. We also looked at how to calculate the length of each and how to use this calculation in code.

Want to continue learning all about Python?

Look no further than our Introduction to Programming Nanodegree program. Don’t delay: It’s your first step towards a career in a field like software development, machine learning, or data science!