Adding/Removing Values to/from a List
Lists are not just for storing values; you can also add or remove values as needed.
In this lesson, we will learn how to add or remove values from a list using the append, remove, and pop methods.
Adding New Values to a List with append
To add a new element to a list, use the append()
method.
append()
adds the new element to the end of the list.
# Adding a value to the list
fruits = ["apple", "banana", "cherry"]
# Add "orange" to the end of the list
fruits.append("orange")
# Output: ["apple", "banana", "cherry", "orange"]
print(fruits)
Since append()
adds an element to the end of the list, you can maintain the order of the original list while adding data.
You can use this when programming tasks such as adding new items to a shopping cart.
Removing Values from a List with remove
To remove a specific value from a list, use the remove()
method.
# Removing a value from the list
fruits = ["apple", "banana", "cherry", "banana"]
# Remove the first "banana" found at index 1
fruits.remove("banana")
# Output: ["apple", "cherry", "banana"]
print(fruits)
One thing to note is that remove()
removes the first element found with the specified value, meaning the one with the smallest index.
If you try to remove a value that is not in the list, a program error will occur.
Retrieving and Removing Values from a List with pop
pop()
retrieves a specific element from the list and removes it simultaneously.
If no index is specified inside the parentheses, pop()
retrieves and removes the last element from the list.
# Retrieving and removing a value from the list
fruits = ["apple", "banana", "cherry"]
# Retrieve and remove the last element in the list
last_fruit = fruits.pop()
# Output: "cherry"
print(last_fruit)
# Output: ["apple", "banana"]
print(fruits)
If you want to retrieve and remove a value from a specific index, you can pass the index inside the parentheses in pop()
.
# Retrieving and removing a value from a specific index in the list
fruits = ["apple", "banana", "cherry"]
# Retrieve and remove the element at index 1 (the second element)
second_fruit = fruits.pop(1)
# Output: "banana"
print(second_fruit)
# Output: ["apple", "cherry"]
print(fruits)
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.