Python Append: How to Use it With Multiple Data Types — Codefather

How do you add an element at the end of a Python list? This is what the Python append method is for and append is not only for lists.

The Python append() method adds an element at the end of an existing list. Also, it modifies the existing list instead of creating a new one. The append method can also be used with other Python data types sets and tuples.

Let’s go through some examples!

How Do You Append to a List in Python?

We will define a Python list and then call the append method on that list.

In this example we are adding a single integer to the end of our list, that’s why we are passing an integer to the append method.

>>> numbers = [1, -3, 5, 8]
>>> numbers.append(10)
>>> print(numbers)
[1, -3, 5, 8, 10]

As you can see the list numbers has been updated and the last element of the list is now the integer we just added.

In your list you can also have mixed data types:

>>> elements = [1, 'cat', 3+2j, 5.14, 'python']
>>> elements.append('tutorial')
>>> print(elements)
[1, 'cat', (3+2j), 5.14, 'python', 'tutorial']

Notice also how the append method updates the existing list and doesn’t return any value back.

>>> result = elements.append('tutorial')
>>> print(elements)
[1, 'cat', (3+2j), 5.14, 'python', 'tutorial', 'tutorial']
>>> print(result)
None

What if we want to add two elements to a list?

Let’s give it a try with append…

>>> numbers = [1, -3, 5, 8]
>>> numbers.append(10, 11)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: append() takes exactly one argument (2 given)

According to the error, the append() method takes only one argument.

What if we append a single list that contains the two numbers?

>>> numbers = [1, -3, 5, 8]
>>> numbers.append([10, 11])
>>> print(numbers)
[1, -3, 5, 8, [10, 11]]

It works but it’s not exactly what we want because now the last element of our list is another list.

We will see later in this tutorial how to add the two elements to the list without having to call the append method twice.

Append a Character to a String

I wonder if I can use the append method to add a character at the end of a string.

After all a string is just a “list” of characters…

>>> animal = 'tiger'
>>> animal.append('s')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'

Hmmm…apparently the append method is not supported by string objects.

Also, remember that…

The string data type in Python is immutable.

This means that to get the new string we want we have to concatenate our current string with the character ‘s’ and assign the result to a new string:

>>> animal = 'tiger'
>>> new_animal = animal + 's'
>>> print(new_animal)
tigers

Append an Element to a Python Dictionary

When you think about appending an element to a dictionary it’s basically the same as setting the value of a new dictionary key.

>>> capitals = {'Italy': 'Rome', 'United Kingdom': 'London'}
>>> capitals['Spain'] = 'Madrid'
>>> print(capitals)
{'Italy': 'Rome', 'United Kingdom': 'London', 'Spain': 'Madrid'}

You can see the updated dictionary after setting the value associated to the key “Spain”.

The append method could make sense when talking about dictionaries if the elements of a dictionary are lists.

For example:

>>> monuments = {'London': [], 'Paris': []}
>>> monuments['London'].append('London Eye')
>>> print(monuments)
{'London': ['London Eye'], 'Paris': []}

We have defined a dictionary whose values are two empty lists.

This means that we can use the append method to add elements to each list in the same way we have done with the value associated to the key “London”.

Append Multiple Items to a List

Before we have seen that when we have tried to append a list with two elements to our list the result was a list inside a list.

So, how can we add two individual elements to the end of a list?

We can use the extend method:

>>> numbers = [1, -3, 5, 8]
>>> numbers.extend([10, 11])
>>> print(numbers)
[1, -3, 5, 8, 10, 11]

Even if we have passed a list of two elements to the extend method, the result is a list in which those two elements have been appended individually at the end of the list.

Exactly what we wanted!

Append Elements to a Tuple

Let’s find out if we can use the append method with a tuple:

>>> numbers = (1.34, 4.56, -4.56)
>>> numbers.append(5.67)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'

The tuple doesn’t have an append method because tuples are immutable.

We can generate a new tuple from the initial one by converting the tuple into a list first.

Then once appended a new number to the list we can convert it to a tuple using the tuple() function.

>>> numbers = (1.34, 4.56, -4.56)
>>> numbers_list = list(numbers)
>>> numbers_list.append(5.67)
>>> numbers = tuple(numbers_list)
>>> print(numbers)
(1.34, 4.56, -4.56, 5.67)

Append Elements to a Set

Now it’s time to append a new element to a Python set.

Do you know if the append method is available for sets?

Let’s find out…

>>> numbers = {1.34, 4.56, -4.56}
>>> numbers.append(5.67)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'set' object has no attribute 'append'

We are not very lucky today… :)

The append method doesn’t exist for a set.

But, what other methods does the set support?

We can find that out by writing the name of our set in the Python shell followed by a dot and then press TAB twice.

All the supported methods will appear in the shell:

>>> numbers.
numbers.add( numbers.intersection( numbers.remove(
numbers.clear( numbers.intersection_update( numbers.symmetric_difference(
numbers.copy( numbers.isdisjoint( numbers.symmetric_difference_update(
numbers.difference( numbers.issubset( numbers.union(
numbers.difference_update( numbers.issuperset( numbers.update(
numbers.discard( numbers.pop(

Looking at the list of methods I have noticed the add method. Let’s try it!

>>> numbers.add(5.67)
>>> print(numbers)
{1.34, -4.56, 4.56, 5.67}

Good to know…

To add an element to a set you can use the add method.

As you can see below the add method only supports one value at a time:

>>> numbers.add(10.23,22.23)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: add() takes exactly one argument (2 given)

And it doesn’t accept lists as parameters:

>>> numbers.add([10.23,22.23])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

Append a List to Another List

This is what we have already seen in one of the previous sections:

>>> numbers = [1, -3, 5, 8]
>>> numbers.append([10, 11, 12, 15])
>>> print(numbers)
[1, -3, 5, 8, [10, 11, 12, 15]]

Using append we have added another list as the last element of our list.

We can use index 4 to access the list and then another index to access any element in the list.

>>> print(numbers[4][0])
10

Makes sense?

What is the Opposite of Append in Python?

It can also be handy to know how to remove an element from the end of a list.

Let’s create a list and then see the methods available for lists in Python:

>>> numbers = [0, 4, -4, 8]
>>> numbers.
numbers.append( numbers.copy( numbers.extend( numbers.insert( numbers.remove( numbers.sort(
numbers.clear( numbers.count( numbers.index( numbers.pop( numbers.reverse(

The first method that might help us is remove:

The remove method removes elements from a list based on their value. Definitely not what we are looking for…

What about the pop method?

This is what we have been looking for. It removes an item at a certain index and the default is the last.

>>> numbers = [0, 4, -4, 8]
>>> numbers.append(10)
>>> numbers.pop()
10
>>> print(numbers)
[0, 4, -4, 8]

You can see that we have added the number 10 at the end of our list with the append method. Then we have removed the same number using the pop method.

Append Rows to a Pandas Dataframe

This is slightly different from the examples we have seen before because it’s not related to Python built-in data types.

Let’s find out how we can append rows to a Dataframe created with the Pandas library.

Firstly, we will define an empty dataframe:

>>> import pandas as pd
>>> df = pd.DataFrame()
>>> print(df)
Empty DataFrame
Columns: []
Index: []

Then using the Dataframe append method we will append two rows to the dataframe.

>>> df = df.append({'Cities': 'London'}, ignore_index=True)
>>> df = df.append({'Cities': 'Paris'}, ignore_index=True)
>>> print(df)
Cities
0 London
1 Paris

We can also append one dataframe to another dataframe.

Here’s how:

>>> df1 = pd.DataFrame({"Cities": ["London"]})
>>> print(df1)
Cities
0 London
>>> df2 = pd.DataFrame({"Cities": ["Paris"]})
>>> print(df2)
Cities
0 Paris
>>> df3 = df1.append(df2)
>>> print(df3)
Cities
0 London
0 Paris

Dataframe df3 is the result of appending df2 to df1.

I have also created a tutorial you can use to practice with Pandas dataframes.

Append a Line to a File

We will complete this tutorial with a type of append that is completely different from the examples covered so far.

This time we will work with files and we will look at how to append a line to a file in Python.

I have created a file with the following content:

$ cat testfile 
line1
line2
line3

To append a line to this file we have to open the file in append mode and then write to the file:

>>> testfile = open('testfile', 'a')      
>>> testfile.write('line4')
5
>>> testfile.close()

To confirm that the file has been updated we can open the file in read mode and use the read function:

>>> testfile = open('testfile', 'r')
>>> print(testfile.read())
line1
line2
line3
line4
>>> testfile.close()

The new line has been added to the file.

As you can see after working with our file we have called the close() function to make sure we don’t consume resources on our system.

If you want to learn a better way to handle files that doesn’t require you to explicitly close every file you open, then have a look at this article about the Python with statement.

Conclusion

We have seen so many ways to append data to different Python data structures.

Which one are you planning to use in your program?

Originally published at https://codefather.tech on February 26, 2021.

I’m a Tech Lead, Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store