Add, Delete, and Edit a list in Python
Here are a few common ways to add, delete, and edit a list in Python.
Adding to Lists
To add to the list of items you can use the .append() or .insert() methods from Python. These two methods will mutate the original array. To use append, you would do something like this:
my_list = [0, 1, 2, 3]
my_list.append(4)
# output: [0, 1, 2, 3, 4]
Keep in mind that append adds the item to the end of the list and doesn't give you any other options.
Unlike append, insert allows you add an item anywhere in a list of items. To use insert, you would do something like this:
my_list = [0, 1, 2, 3]
my_list.insert(4, 4)
# output: [0, 1, 2, 3, 4]
If you want to add a value at a particular index, the insert method takes in two arguments. The first one is at what index (location) you want to insert the new value and the second argument is the value you want to insert.
Removing from Lists
Python provides 4 options to remove elements from a list.
The
del()
function - mutates original list.The
list.pop()
method - mutates original list.The
list.remove()
method - mutates original list.The
list.clear()
method - mutates original list.
The del()
function removes elements by index or range of indices.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
del(my_list[0])
print(my_list)
#output: [2, 3, 4, 5, 6, 7, 8, 9, 10]
del(my_list[1:4]
print(my_list)
#output: [2, 6, 7, 8, 9, 10]
# 3,4,5 is between the 1 and 4 indices.
The .pop()
method removes the element at the index you gave as an argument and if no argument is provided, it will remove the last element of the list. It will also return the value of the removed element.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list.pop()
#output: 10
my_list.pop(1)
#output: 2
The .remove()
method removes the element that is passed as an argument and it searches by value instead of index.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list.remove(10)
print(my_list)
#output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
The .clear()
method removes all the elements from a list.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list.clear()
print(my_list)
#output: []
Editing an item in a lists
To edit a value in a list of items you can do the following:
my_list = [0, 1, 2, 3]
my_list[0] = 4
print(my_list)
# => [4, 1, 2, 3]
By access the index and setting it to a new value, it will update the original list to the new value. However, you can not extend the list so if you try to access an index that doesn't exist, you will get the IndexError: list assignment index out of range
error.