Python List append() Method
The Python List append() method is used to add new objects to a list. This method accepts an object as an argument and inserts it at the end of the existing list. The object argument can be of any type, as a Python list can hold multiple data type elements. However, if the object is itself a new list with multiple elements, it is considered as a single object and the size of the existing list will only be increased by 1.
Since we can append only a single object to the list at a time using this method, the time complexity of the append() method will be O(1).
Syntax
Following is the syntax for the Python List append() method −
list.append(obj)
Parameters
Return Value
This method does not return any value but updates existing list.
Example
The following example shows the usage of Python List append() method. Here, we are creating a simple list containing string elements and trying to append another string element to it using this method.
aList = ['123', 'xyz', 'zara', 'abc'];
aList.append('2009');
print("Updated List : ", aList)
When we run above program, it produces following result −
Updated List : ['123', 'xyz', 'zara', 'abc', '2009']
Example
Now, let us consider an example scenario where we append the missing days of a week into a Python list. In this example, a list is created containing the days of the week ['Mon', 'Tue', 'Wed']. Using the append() method, we will try to append the remaining days of the week in two ways: appending one element at a time and appending a list.
list = ['Mon', 'Tue', 'Wed']
print("Existing list\n",list)
# Append an element
list.append('Thu')
print("Appended one element: ",list)
# Append a list
list.append(['Fri','Sat'])
print("Appended a list: ",list)
Running the above code gives us the following result −
Existing list
['Mon', 'Tue', 'Wed']
Appended one element: ['Mon', 'Tue', 'Wed', 'Thu']
Appended a list: ['Mon', 'Tue', 'Wed', 'Thu', ['Fri', 'Sat']]
Example
The append() method can also be called on a list containing other data types rather than just strings. In the following example, we are trying to append an integer object to an integer list using this method.
# Creating an integer list
nums = [1, 2, 3, 4]
# Displaying the list
print('List Before Appending:')
print(nums)
print()
# Appending an element to the nums
# 5 will be added at the end of the nums
nums.append(5)
# Displaying the list
print('List After Appending:')
print(nums)
If you run the above program, you will get the following result −
List Before Appending:
[1, 2, 3, 4]
List After Appending:
[1, 2, 3, 4, 5]
python_lists.htm