Python: list.append()

Python Tutorials

Summary: In this tutorial, we will learn to add new items to the Python list data structure using the built-in append() method.

The list data structure in Python is dynamic. It means we can change its size by adding or removing elements.

The list.append(x) method is one of the Python built-in methods that append (add) new item x to the end of the list.

For example, in the following code, we are appending new items to the existing list using the append method:

>>> l = [1, 2, 3, 4]
>>> l.append(5)
>>> print(l)
[1, 2, 3, 4, 5]

Parameters and Return Type

The list.append(x) method accepts only one positional argument, which is the new item that needs to be attached to the existing list.

It does not return any data.

Examples using list.append()

Example 1: Append a new item to an existing list in Python

>>> l = ['Python', 'Java', 'C++']
>>> l.append('R')
>>> print(l)
['Python', 'Java', 'C++', 'R']

Example 2: Append a list to another existing list using the list.append() method

>>> l = [1, 2, 3]
>>> l.append([4, 5, 6])
>>> print(l)
[1, 2, 3, [4, 5, 6]]

As we can see, the list which we have added is nested inside the parent list. If we need to combine elements of two lists together then instead of the append method we should add them together using the + operator on lists.

>>> l = [1, 2, 3]
>>> l = l + [4, 5, 6]
>>> print(l)
[1, 2, 3, 4, 5, 6]

Conclusion

The list.append(x) method appends a new item to an existing list in Python.

We should use this method when we need to append any item/object to the end of any Python list.

Leave a Reply

Your email address will not be published. Required fields are marked *