Removing Items from a List
There are many ways to remove values from a list, we will be exploring most of them.
With removal, there are a lot of dangerous situations that can occur. It is advised to understand each technique before thinking about value removals.
Removal by a Target Value
.remove(target)
method will remove the first occurance of the targetted value if it exists in the list.
If the target_value doesn’t exist, it will produce an error.
Removal by Index
.pop(target_index)
will remove a value located at the target_index
and RETURN THE VALUE.
If the target_index goes beyond the list size, it will produce an error.
pop()
without an target index returns and removes the last value
Removing All Items in a List
.clear()
is a method that will empty out its list.
Introduction to del
del
del
is used to delete objects in Python. The concepts of “objects” are discussed in a future course!
del
can delete an entire instance of a list
Notice that since the variable was deleted, we get an error say that the a_list
was never created.
del
can delete a single item in a list by indexing
There are no errors here since we are only deleting single items from the list.
del
can delete via slicing
Notice that the first three items were deleted from a_list.
MAJOR DANGER: Deletion During Iteration
It is very common for beginner programmers to delete while iterating the targeted list.
Observe:
Explanation:
The print statement inside the iteration prints ‘kiwi’
The print statement of ‘kiwi’ should have been impossible since ‘kiwi’ was deleted
This happens because a for loop never re-checks the value of a_list
Recommendations:
Use while loops and index-based deletion
Make a copy of the list, execute deletion on the copy
Last updated