Lessons

Python Basics

Python Variables

Operators in Python

Conditional Statements in Python

Python Lists

Python Tuples

Python Sets

Python Dictionaries

Loops in Python

Python Arrays and Functions

Conclusion

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
1
2
3
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")  # Removing "banana" from the list
print(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
1
2
3
thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
thislist.remove("banana")  # This removes the first "banana"
print(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
1
2
3
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)  # This removes the item at index 1 (second item)
print(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
1
2
3
thislist = ["apple", "banana", "cherry"]
thislist.pop()  # This removes the last item
print(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
1
2
3
thislist = ["apple", "banana", "cherry"]
del thislist[0]  # This removes the item at index 0 (first item)
print(thislist)  # Output: ['banana', 'cherry']

Note:

The del keyword can also delete the entire list.

Example:

Delete the entire list:

python
1
2
3
thislist = ["apple", "banana", "cherry"]
del thislist  # This deletes the entire list
# 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
1
2
3
thislist = ["apple", "banana", "cherry"]
thislist.clear()  # This empties the list
print(thislist)  # Output: []

Frequently Asked Questions