Use remove()
method to remove elements from the list in Python. Python Lists have various built-in methods to remove items from the list.
list.remove(element)
The remove()
method removes the first matching element from the list.
Remove element from list Python
Simple example code.
pn = [2, 3, 5, 7, 9, 11]
# remove 9 from the list
pn.remove(9)
print(pn)
# another exmaple
fl = ['Iris', 'Orchids', 'Rose', 'Lavender']
fl.remove('Orchids')
print(fl)
Output:
Remove an item from a list using list comprehension
list1 = [1, 9, 8, 4, 9, 2, 9]
# to remove list element 9
list1 = [ele for ele in list1 if ele != 9]
print(list1)
Output: [1, 8, 4, 2]
Delete an element from a list using the del
list1 = [1, 9, 8, 4, 9, 2, 9]
# Remove list element at 1
del list1[1]
print(list1)
Output: [1, 8, 4, 9, 2, 9]
Delete an element from a List using pop()
We can remove the element at the specified index and get the value of that element.
list1 = [1, 9, 8, 4, 9, 2, 9]
a = list1.pop(1)
print("Item popped :", a)
print("After deleting the item :", list1)
Output:
Item popped: 9
After deleting the item : [1, 8, 4, 9, 2, 9]
The remove()
method removes the first occurrence of a specified value. The del
statement removes the item at a specified index. The pop()
method removes the item at a specified index and returns it. If no index is specified, it removes and returns the last item in the list.
Do comment if you have any doubts or suggestions on this Python list topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.