Python Remove Item from List
Remove List Items in Python
In Python, lists are mutable data structures that allow you to remove items easily. This lesson will cover different methods for removing items from a list, including removing specified items, removing items by index, and clearing the list entirely.
1. Remove Specified Item
To remove a specific item from a list, you can use the remove()
method. This method takes the value of the item you want to remove as an argument.
Example:
Remove "banana":
python
1thislist = ["apple", "banana", "cherry"]
2thislist.remove("banana") # Removing "banana" from the list
3print(thislist) # Output: ['apple', 'cherry']
Note:
If there are multiple occurrences of the specified item, the remove()
method will only remove the first occurrence.
Example:
Remove the first occurrence of "banana":
python
1thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
2thislist.remove("banana") # This removes the first "banana"
3print(thislist) # Output: ['apple', 'cherry', 'banana', 'kiwi']
2. Remove Specified Index
You can also remove items by their index using the pop()
method. This method removes the item at the specified index and returns that item.
Example:
Remove the second item:
python
1thislist = ["apple", "banana", "cherry"]
2thislist.pop(1) # This removes the item at index 1 (second item)
3print(thislist) # Output: ['apple', 'cherry']
Note:
If you do not specify an index, the pop()
method will remove and return the last item in the list.
Example:
Remove the last item:
python
1thislist = ["apple", "banana", "cherry"]
2thislist.pop() # This removes the last item
3print(thislist) # Output: ['apple', 'banana']
3. Using the
The del
keyword can also be used to remove items from a list by specifying the index.
Example:
Remove the first item:
python
1thislist = ["apple", "banana", "cherry"]
2del thislist[0] # This removes the item at index 0 (first item)
3print(thislist) # Output: ['banana', 'cherry']
Note:
The del
keyword can also delete the entire list.
Example:
Delete the entire list:
python
1thislist = ["apple", "banana", "cherry"]
2del thislist # This deletes the entire list
3# print(thislist) # This will raise a NameError since the list no longer exists
4. Clear the List
If you want to empty a list but keep the list itself, you can use the clear()
method. This method removes all items from the list.
Example:
Clear the list content:
python
1thislist = ["apple", "banana", "cherry"]
2thislist.clear() # This empties the list
3print(thislist) # Output: []