Removing an Element from a List in Python
To remove a value from a list, you can use the remove method or the pop method.
The remove Method
list_name.remove(value)
If the element doesn't exist in the list, the remove method will return an error.
The pop Method
list_name.pop(index)
The pop method uses the index of the list as a parameter instead of the value.
If the index is greater than the length of the list, the pop method will raise an error.
Additionally, unlike remove, the pop method returns the removed element.
The remove Method
Given the following list:
year = [2010, 2011, 2012, 2013]
To delete the first element, you would type:
year.remove(2010)
After the change, the list becomes:
[2011, 2012, 2013]
The pop Method
Given the following list:
year = [2010, 2011, 2012, 2013]
To remove and return the first element, you would type:
year.pop(0)
After the change, the list becomes:
[2011, 2012, 2013]
How to Remove Multiple Elements
To remove two or more contiguous elements from a list, you can use slicing.
You specify a range where the first element is included and the second element is excluded:
list[start_included:end_excluded] = []
This assigns the specified range to an empty list [].
A Practical Example
Given the following list:
year = [2010, 2011, 2012, 2013]
To remove the first two elements, you would type:
year[0:2] = []
After the change, the list becomes:
[2012, 2013]
Now, to remove the last element, you would type:
year[-1:] = []
The final list becomes:
[2012]
And so on.
The del Statement
Another way to remove elements from a list is by using the del statement:
del list_name[index]
The del statement can delete individual elements or slices of elements.
It is often the simplest method to use.
A Practical Example
Given the following list:
year = [2010, 2011, 2012, 2013]
To delete the first two elements, you would type:
del year[0:2]
The left limit is included (0), while the right limit is excluded (2).
The final result is:
[2012, 2013]
And so on.
