How do I remove items from a list
delif you only want to remove an item by index
pop()if you want to return the item value and then delete it
remove()if you want to return an item value by value rather than index
Python provides different options to remove items from your existing list. As expected, each option is best used for a different use case.
How to remove an element from a list by index
>>> my_list = [1,2,3,4,5] >>> del my_list >>> print(my_list) [1,3,4,5]
del's sole purpose is to delete objects during runtime. It is not limited to delete list items, but in fact applicable to any other object. For example, you could use it to delete your entire list.
You should be careful with
del as it will raise an exception if the object does not exist. For example, if you use an invalid index of your list, Python will simply raise an error.
>>> my_list = [1,2,3,4,5] >>> del my_list >>> print(my_list) NameError: name 'my_list' is not defined
del statement does not return anything. If you want to retrieve the value before deleting it, then you should look into using the list method
>>> my_list = [1,2,3,4,5] >>> a = my_list.pop(1) >>> print(a) 2 >>> print(my_list) [1,3,4,5]
Delete a list element by value
>>> my_list = [1,2,3,4,5,1] >>> my_list.remove(1) >>> print(my_list) [2,3,4,5,1]
remove(value) takes the targeted value instead of an index as we saw with
pop(). The method runs your through list and deletes the first occurrence of the value. Python will throw an error in case you are trying to remove a value which does not exist in your list.
You could use a list comprehension if you want to remove all instances of a value
>>> my_list = [1,2,3,4,5,1] >>> value_to_remove = 1 >>> my_modified_list = [value for value in my_list if value != value_to_remove] >>> print(my_modified_list) [2,3,4,5]
How do I remove the first item from a list
# delete first item using pop >>> my_list = [1,2,3,4,5] >>> my_list.pop(0)
# delete first item using del >>> my_list = [1,2,3,4,5] >>> del my_list