Connect with us

Website Tutorials

How to Append an Item to a Python Array

Published

on

How to Append an Item to a Python Array

Appending an item to a Python array is easy, though the terminology requires some clarification. By default, Python doesn’t use “arrays” as is commonly understood in most programming languages but instead uses “lists”, which serve the same functionality for most ordinary use cases. However, there are some important differences between the two, and I’ll explain the differences below, including when to use each.

Appending an Item to a Python Array

To explicitly use arrays instead of lists in Python, you need to import the “array” module. Here’s a series of commands designed to show you how to create an array, append an item to it, and print the output:

import array
my_array = array.array('i', [1, 2, 3])
my_array.append(4)
print(my_array)

As you can see, first we import the “array” module that comes in-built with the Python installation. Next, we create the array.

Specifying the Array

Unlike a list, an array in Python can only hold a specific data type. When creating a new array, we have to specify which data type the array is going to hold. Every data type is indicated by a certain character, and when dealing with integers, we use the letter “i”. Here’s a partial list of the letters we use for different data types:

  1. Integers – “i”
  2. Floats – “f”
  3. Long integers – “l”
  4. Characters – “b”

Note that there’s no data type called “text” for array storage. The closest you can get to storing text in a Python array is by using the Unicode character type “u”. This is because arrays in Python are used only for storing primitive data types and not composite ones like strings. So if you want to store an array of texts, it’s better to use lists or strings instead.

To specify the array in Python, we use something like this:

my_array = array.array('i', [1, 2, 3])

In this example, we indicate that “my_array” will hold integers, thanks to the “i” that we use in the beginning. And we then specify the integers we will be storing.

Advertisement

Appending an Element to the Python Array

Once we’ve created a Python array, appending to it is simple. Just:

my_array.append(4)

This appends the integer “4” to the array. And we can then print the variable as usual to verify. Here’s a screenshot of what it looks like:

Appending Items to an Array in Python
Appending Items to an Array in Python

As you can see, the new element “4” has been appended to the array.

Invalid Append Operations

Since, unlike a list in Python, an array can only hold a specific data type, if you try and add something to the array that doesn’t belong, it throws an error:

Trying to Append a String to a Numeric Array
Trying to Append a String to a Numeric Array

In the above screenshot, I’m trying to add a string ‘test’ to an array that I’ve already designated as being a string array. Python throws an error telling me that the ‘str’ object cannot be interpreted as an integer, as expected.

Appending an Item to a List Instead of an Array

Lists are the general-purpose equivalent of arrays in Python. If you’re reading this article, there’s a good chance that you’re searching for information about appending items to a list without realizing that arrays and lists are different. If that’s the case, here’s how to append an item to a Python list instead of an array.

Here’s the code to append an item to a list:

Advertisement
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)

As you can see, the process of creating and appending an item to a list in Python is practically the same as that of an array, except for the initial declaration statement. Instead of importing the “array” module, initializing the array, and specifying the data type of the contents of the array, we just add the elements as shown above as if it were a regular variable.

Here’s the output of the above code:

Python Append to List
Python Append to List

So far, the output of the list isn’t very different from that of an array. After all, in the previous example, we just added another number to an array that was already specified as an integer array. But we also saw how adding a string to it, generates an error. Let’s do the same thing with a list and see what happens. Here’s a screenshot:

Appending a String to a List
Appending a String to a List

In the above screenshot, I use the code:

my_list.append ("Hello there")

To append a string to a list that, so far, has nothing but numbers. Yet, it doesn’t generate an error, and when I print the “my_list” variable, I get the expected output. This is the fundamental difference between a list and an array.

Differences Between Arrays and Lists in Python

If you can run pretty much the same command to append something to an array or a list in Python, then what’s the difference between the two?

Arrays are Specific to a Certain Data Type

As we’ve seen above, the main functional difference between lists and arrays is that the latter are restricted to certain data types. This can’t be the only differentiating factor between them, though, because otherwise, no one would choose to use an array instead of a list. So this is only the most obvious, outward-facing difference.

Advertisement

Arrays can be More Efficient

For most ordinary use cases, the performance differences between arrays and lists don’t matter. But in specialized circumstances, the difference can be huge. Take scientific data for example. Such data sets can be extremely large, and working with them means you need to squeeze maximum efficiency out of each operation.

An array stores its data contiguously, which means that processors have an easier time accessing the next data item. Lists, on the other hand, are arrays of pointers to data objects. While the array of pointers is itself stored on contiguous memory, the data objects need not be.

Another reason for the efficiency of lists is that since we know the data type of each element, we can allocate the same amount of memory per item on the disk. There’s no need for a separate space indicating the data type. So arrays are more “closely packed” than lists, in terms of data storage.

But Resizing an Array is More Inefficient

Unfortunately, the performance benefits of arrays only shine if you don’t need to resize them frequently. Because arrays are stored contiguously, the system initially “overallocates” memory so that further append operations to arrays in Python don’t cause a problem. But if it goes beyond that, then the system triggers a resize event, and it has to allocate a new block of contiguous memory with overallocation and then copy over the old array into the new one.

Since you typically use arrays for very large data sets, this kind of trigger is very memory-intensive. So if you’re going to use an array, it’s best to ensure that you won’t need to resize it often.

Advertisement

Conclusion

Appending an element to an array in Python is as simple as importing the necessary array module, and then issuing an append command. However, you might find lists to be a more appropriate tool for your needs, and you should reserve arrays only for special situations where you’re dealing with vast amounts of structured data that don’t require different data types or a lot of resizing, as these can wipe out the efficiency gains from using arrays.

Stephen Oduntan is the founder and CEO of SirsteveHQ, one of the fastest growing independent web hosts in Nigeria. Stephen has been working online since 2010 and has over a decade experience in Internet Entrepreneurship.

Continue Reading
Advertisement
Comments

Trending

Copyright © 2024 SirsteveHQ. All Rights Reserved.