Append an Element to a List in Python
Appending an element to a list in Python is adding new items to an existing list. The append()
method is used to add an item to the end of the list.
Syntax of the append()
Method
The append()
method is called on a list and takes a single argument, which is the element you want to add.
list_name.append(element)
Here, list_name
refers to the list to which we are appending an element, and element
is the value to be added.
Examples
1. Append a Single Element to a List
Let’s start with a basic example of appending an element to a list.
# Creating a list of numbers
numbers = [1, 2, 3, 4]
# Appending an element
numbers.append(5)
# Printing the updated list
print("Updated List:", numbers)
Output:
Updated List: [1, 2, 3, 4, 5]
Here, the number 5
is added to the end of the list using append()
.
2. Append a String to a List
The append()
method can also be used to add a string to a list.
# Creating a list of fruits
fruits = ["apple", "banana", "cherry"]
# Appending a new fruit
fruits.append("orange")
# Printing the updated list
print("Updated Fruits List:", fruits)
Output:
Updated Fruits List: ['apple', 'banana', 'cherry', 'orange']
3. Append a List to Another List
If we append a list to another list, the entire list is added as a single element (creating a nested list).
# Creating a list of numbers
numbers = [1, 2, 3]
# Creating another list
more_numbers = [4, 5, 6]
# Appending the second list
numbers.append(more_numbers)
# Printing the updated list
print("Updated List:", numbers)
Output:
Updated List: [1, 2, 3, [4, 5, 6]]
Notice that the second list more_numbers
is added as a single element, resulting in a nested list.
4. Append an Element Inside a Loop
We can also append elements to a list inside a loop.
# Creating an empty list
squares = []
# Appending squares of numbers from 1 to 5
for i in range(1, 6):
squares.append(i ** 2)
# Printing the updated list
print("List of squares:", squares)
Output:
List of squares: [1, 4, 9, 16, 25]
Here, we append the square of each number from 1 to 5 to the squares
list inside a loop.
Points to Remember
- The
append()
method is used to add a single element to the end of a list. - If a list is appended to another list, it is added as a single element, creating a nested list.
append()
is useful when dynamically building a list, such as in loops.