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.

# .remove() example

a_list = ['apple', 'oranges', 'kiwi', 'honeydew', 'apple']
a_list.remove('apple')
a_list.remove('kiwi')

print('a_list:', a_list)
a_list: ['oranges', 'honeydew', 'apple']

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

# .pop() example

a_list = ['apple', 'oranges', 'kiwi', 'honeydew', 'apple']
removed1 = a_list.pop()
a_list.pop(2)


print('a_list:', a_list)
print('removed1:', removed1)

Removing All Items in a List

.clear() is a method that will empty out its list.

Introduction to 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:

  1. Use while loops and index-based deletion

  2. Make a copy of the list, execute deletion on the copy

Last updated