How to Remove an Element from a List in Python
Python provides many ways to help us remove a specific element from a list. Using the built-in functions Remove() , pop() and clear() . We can also use the del keyword to remove elements from the list.
Method 1: Use the Remove() function
Items can be removed from the list using the built-in Remove() function but an error is raised if the item is not in the list. The Remove() function removes only one element at a time, the Remove() function removes only the selected element.
Note: The Remove() function removes only the first occurrence of the searched element.
Example:
# Create a list
List = [1, 2, 3, 4, 5, 6,7, 8, 9, 10]
print("original list:")
print (List)
# Remove items from the list
# Remove() using a function
List. remove(3)
List. remove(6)
print("\nThe list after removing two elements: ")
print(List)
The output will be:
original list:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List after removing two items:
[1, 2, 4, 5, 7, 8, 9, 10]
Method 2: Use the pop() function
The pop() function can also be used to remove and return an item from the list, but by default it only removes the last item from the listundefined list, to remove an element from a specific position in the list, the index of the element is passed as an argument to the pop() function.
Example:
# Create a list
List = [1, 2, 3, 4, 5, 6,7, 8, 9, 10]
print("original list:")
print (List)
# Remove items from the list
# pop() using a function
List.pop(2)
print("\nThe list after removing the element with index 2: ")
print(List)
The output will be:
original list:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The list after removing the element with index 2:
[1, 2, 4, 5, 6, 7, 8, 9, 10]
Method 3: Use the clear() function
The clear() function removes all elements from the list. Clears the list completely and returns nothing. It requires no arguments and returns no exception if the list is already empty.
Example:
# Create a list
List = [1, 2, 3, 4, 5, 6,7, 8, 9, 10]
print("original list:")
print (List)
# Remove items from the list
# clear() using a function
List. clear()
print("\nThe list after removing all its elements :")
print(List)
The output will be:
original list:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List after removing all its elements:
[]
External sources:
Lists - documents undefined Official Python
If you have any questions or concerns, leave them in the comments
Tags
Python python data types python lists Python List remove() Method Python List pop() Method Python List clear() Method Remove an Element from a List in Python
Share page
About author
Ahmed Obaid
Hello, I am Ahmed Obaid, an Egyptian Arabic programmer. I would like to put my experiences learning Python on this site So that it will be a reference for you and me as well.
Sign up to leave a comment