Click for All Topics
.remove()
method takes exactly one argument and it doesn’t return anything..remove()
method with a list and pass an element as an argument it first iterates over the elements of the list and finds the passed element, if an element is found it removes the element from the list if not found then it will throw an error ValueError
..remove()
method is O(n).
Syntax –
list.remove(element)
Parameter –
Example –
my_list=[20,40,60,80,100]
print("Original list:",my_list)
my_list.remove(60)
print("Modified Original list:",my_list)
# Output -
# Original list: [20, 40, 60, 80, 100]
# Modified Original list: [20, 40, 80, 100]
.remove()
method.Example 2- Removes the element from the list based on the condition
# remove all odd elements from a list
my_list=[1,2,3,4,5,6,7,8,9,10]
print("Original list:",my_list)
i=0
while i
💡 We do not use
.remove()
method inside a for loop because for loop runs in the range of list or size of list and when we use.remove()
method it will affect the range of list.Example 3- Removes all duplicate elements from the list
lst=['a','b','c','d','a','a','e','f']
print("Original list:",lst)
i=0
while (i
Example 4- Remove a list from a list
my_list=['hello','Python','remove',['edSlash','official']]
print("Original list:",my_list)
my_list.remove(['edSlash','official'])
print("Modified Original list:",my_list)
# Output -
# Original list: ['hello', 'Python', 'remove', ['edSlash', 'official']]
# Modified Original list: ['hello', 'Python', 'remove']
Example 5- Remove an element that doesn’t exist
my_list=['hello','Students','this','is','edSlash']
print("Original List :",my_list)
my_list.remove('anurag')
print("\nModified Original List:",my_list)
# Output -
# Original List : ['hello', 'Students', 'this', 'is', 'edSlash']
# Traceback (most recent call last):
# File "/home/main.py", line 3, in
# my_list.remove('anurag')
# ValueError: list.remove(x): x not in list
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India