How to Use Python to Append to a List

Adam Bertram

Adam Bertram

Read more posts by this author.

In Python, lists are a common data structure that holds multiple elements. In this post, learn how you use Python to append to a list.

Appending to a List with Append()

Let’s say you’ve got a list (or array for you non-Pythonistas) with a set number of string elements represented by colors.

>>> colors = ['blue','red','green']

To append an element in Python to append to a list, we can use the append() method. This method pushes a list element onto the end.

For example, perhaps we need to add the color black to the colors list we just created. To do that, we’d call the append() method and pass the string black as the argument.

>>> colors.append('black')

The colors list should now have the black element appended to it. To verify, simple reference the colors list. Below, you can see that black has been appended to the list.

>>> colors
['blue', 'red', 'green', 'black']

Appending to a List with Extend()

Alternatively, you can also use the extend() ( list method to append to a list. Although this time, you’re not appending a single element but another list.

Perhaps you need to add multiple colors to our colors list.

>>> colorsToAdd = ['yellow','pink']
>>> colors.extend(colorsToAdd)
>>> colors
['blue', 'red', 'green', 'black', 'yellow', 'pink']

The extend() method merges two lists together and appends another list to the end of the original.

Subscribe to Adam the Automator

Get the latest posts delivered right to your inbox

Looks like you're offline!