Contents
To append or add an item to Python List, use append() function. List.append() function modifies the list in place and returns None.
In this tutorial, we shall learn how to use append() function to append an item at the end of List, with some example programs.
Syntax – List.append()
The syntax of using append() function with a Python List is given below.
mylist.append(new_element)
where new_item is appended to the list mylist.
Example 1: Add an Item to the List
In the following example program, we shall create a list with some initial values and add an item to the list using append() function.
Python Program
#a list
cars = ['Ford', 'Volvo', 'BMW', 'Tesla']
#append item to list
cars.append('Audi')
print(cars)
Run When you run this program, the new item Audi is appended to the cars list. When the list is printed out, you will see that there are five items in the list.
Output
['Ford', 'Volvo', 'BMW', 'Tesla', 'Audi']
The new item is appended at the end of the given list.
Example 2: Add multiple Items to List
In the following example program, we shall create an empty list and add an item to the list using append() function. The process should remain same as that of the previous example.
Python Program
#an empty list
cars = []
#append items to list
cars.append('Audi')
cars.append('Volvo')
print(cars)
Run As there are no elements in the given list, append() function places the item in the list. First with 'Audi'
and then 'Volvo'
.
Output
['Audi', 'Volvo']
Chaining of append() Function
Since the append() function returns None, we cannot apply chaining as shown below.
list.append(item1).append(item2)
The above statement returns an error: AttributeError: ‘NoneType’ object has no attribute ‘append’.
Summary
In this tutorial of Python Examples, we learned how to use append() function on a list, to add or append an item to the end of the given list.
Related Tutorials
- Python – Check if List Contains all Elements of Another List
- Python List of Dictionaries
- Python Program to Find Duplicate Items of a List
- Python List of Lists
- Python Program to Find Unique Items of a List
- Python – Check if Element is in List
- Python List without Last Element
- Python List of Functions
- Python – How to Create an Empty List?
- How to Reverse Python List?