Guide to Python's append() Function

Introduction

Basic data types in Python allow us to store a single value under a symbolic name. This roughly follows the mathematical notation of variables. In a way, a name is assigned to a value, so you don't need to remember the actual value, nor its address in computer memory, just a simple, illustrative name.

But, if you need to store a collection of values under one variable name, basic data types won't do the job. You'll need to use more complex data structures. Python has four data types for storing a collection of values under the same name - Tuple, Set, Dictionary, and List. We'll focus on the latter in this article.

A List is a Python data type similar to an array in any other programming language. It stores an ordered collection of values under the same name. Also, it allows duplicate values, as well as changing values of stored elements. The only difference between a List and any usual array is that not all the elements of a List need to have the same data type (it's heterogeneous). For example, one List may contain integer elements, floating-point numbers, strings, as well as other Lists, and any other data type elements:

example_list = [1, 3.14, 'abcd', [4, 3, 2, 1]]

Note: You create a Python List by listing its elements between two square brackets - [...]. Each element is separated by a comma - ,. Python has an array type, separate from Lists and shouldn't be confused with Lists.

In this guide, we'll take a look at how to add elements to the end of a List in Python, how to merge lists, etc. using the append() method, and compare it to other methods used to add elements to a List - extend() and insert().

How To Append Elements to a Python List Using append()

Appending elements to a List is equal to adding those elements to the end of an existing List. Python provides several ways to achieve that, but the method tailored specifically for that task is append(). It has a pretty straightforward syntax:

example_list.append(element)

This code snippet will add the element to the end of the example_list (which is of list type). As we've stated before, a list can contain elements of different data types. Therefore, element can be of any possible data type - int, float, str, list, tuple, and so on.

In the following sections, we'll go over some practical examples illustrating how to append an individual element to a list, as well as how to append one list to another.

Note: In the following examples, we use a List containing elements of different types.

How To Add a Single Element to the End of a Python List

Adding a single element illustrates the main purpose of the append() method in Python. Let's assume you have an example list:

example_list = [1, 3.14, 'abcd']

You would add 5 to the end of the exampe_list in the following way:

example_lsit.append(5)

Now, the example_list will have 5 added to its end:

[1, 3.14, 'abcd', 5]

How To Append One List to Another in Python

Assume you have two lists and want to append one to another:

example_list = [1, 3.14, 'abcd']
secondary_list = [4, 3, 2, 1]

The append() method doesn't provide a way to append two lists together in one method call. If you try to append those two lists using append(), the whole secondary_list will be added as a single element of the example_list, creating a nested list:

example_list.append(secondary_list)
print(example_list)

Now, the example_list contains the following elements, which are probably not what you wanted in the first place:

[1, 3.14, 'abcd', [4, 3, 2, 1]]

Appending one list into another using append() is achieved by iterating over all elements of a list we want to append and appending each of them to the original List :

for element in secondary_list:
    example_list.append(element)

print(example_list)
Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

That way, we've appended the secondary_list to the end of the example_list:

[1, 3.14, 'abcd', 4, 3, 2, 1]

Alternatives to append() in Python

Python List has a couple more methods for adding elements besides append(). Most notably, extend() and insert(). In the following subsections, we'll get into the differences between them and the append() method.

append() vs extend()

As we've seen in previous sections, append() is intended to add one element to the end of a List. On the other hand, extend() is used to add multiple elements to the end of a List - effectively, it appends one list to another. Let's see how extend() works:

example_list = [1, 3.14, 'abcd']
secondary_list = [4, 3, 2, 1]

example_list.extend(secondary_list)
print(example_list)

Output:

[1, 3.14, 'abcd', 4, 3, 2, 1]

Note how extend() appends two lists in one call, and the append() needs to be called one time for each element of a List you want to append! It's a handy method to remember as an alternative.

append() vs insert()

There is no way to insert an element to a specific place in a List using append(), it automatically adds it to the end of a List. That's where insert() comes into view!

Unlike append() and extend(), it accepts two arguments - one is the element you want to insert, and the other is the index of that element in a List.

For example, if you want to add 'asdf' to the end of the example_list you would use example_lsit.append('asdf'), as we've seen in previous sections. But if you want to add it to a specific place, say, between 3.14 and 'abcd', you must use insert():

example_list = [1, 3.14, 'abcd']
# Insert element `asdf` on the index `2`
example_list.insert(2, 'asdf')

print(example_list)

This results in:

[1, 3.14, 'asdf','abcd']

Note the difference in indexing of the original and resulting lists. In the original example_list, the element on index 2 is 'abcd'. After adding 'asdf', it is on the index 2, and the 'abcd' is shifted to the index of 3.

Conclusion

After reading this guide, you should have a better understanding of how to use append() method on Python Lists and how it compares to other Python methods for adding elements to a List.

For a more in-depth comparison of those methods, you should definitely take a look at the following guide - append() vs extend() vs insert() in Python Lists.

Last Updated: April 6th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Project

Building Your First Convolutional Neural Network With Keras

# python# artificial intelligence# machine learning# tensorflow

Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

David Landup
David Landup
Details
Course

Data Visualization in Python with Matplotlib and Pandas

# python# pandas# matplotlib

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

David Landup
David Landup
Details

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms