What does.append do in Python?
Introduction
The append() method in Python is a built-in function that allows you to add elements to the end of a list. In this article, we will explore what it does, its different variations, and its implications on your Python code.
What does.append do in Python?
Append in Plain Python
my_list = []
my_list.append(1)
print(my_list) # [1]
In this example, my_list is an empty list. When we append the number 1 to it, it becomes a new list with a single element: [1].
Append with Multi-Dimensional Lists
my_list = [[1, 2], [3, 4]]
my_list.append([5, 6])
print(my_list) # [[1, 2], [3, 4], [5, 6]]
Here, my_list is a 2D list. When we append another 2D list [5, 6] to it, it becomes a new 2D list with three elements: [1, 2, 5, 6].
Append with Matrices
import numpy as np
my_matrix = np.array([[1, 2], [3, 4]])
my_matrix = np.vstack((my_matrix, [5, 6]))
print(my_matrix)
In this example, my_matrix is a 2D NumPy array. When we append another 2D array [5, 6] to it using np.vstack(), it becomes a new 2D array with three rows: [1, 2, 5, 6].
Append with List Comprehensions
my_list = [1, 2, 3]
my_list.append([4, 5, 6])
print(my_list) # [1, 2, 3, [4, 5, 6]]
Here, my_list is an existing list. When we append a new list [4, 5, 6] to it, it becomes a new list my_list with a new sub-list [4, 5, 6]. Note that the new sub-list is added as a separate element at the end of the original list.
Append with Python’s Built-in Functions
Python’s built-in functions, such as tuple(), zip(), and sorted(), have append() methods.
my_tuple = ()
my_tuple.append(1)
print(my_tuple) # ()
my_tuple.append(2)
print(my_tuple) # (1, 2)
my_tuple = (1, 2)
my_tuple.append(3)
print(my_tuple) # (1, 2, 3)
Note that the append() method returns a new tuple (or list, or other type) with the added element.
