How to Delete Element from List in Python
Learn how to delete elements from a list in Python with our easy-to-follow tutorial. …
Updated July 30, 2023
Learn how to delete elements from a list in Python with our easy-to-follow tutorial.
Definition of Deleting an Element from a List
Deleting an element from a list in Python means removing a specific item or value from the list, leaving the remaining items intact. This can be useful when you need to update your data or remove unnecessary values.
Step-by-Step Explanation
To delete an element from a list in Python, you’ll use various methods and functions. Here’s a step-by-step guide:
Method 1: Using del
Statement
The most straightforward way to delete an element is by using the del
statement. This method requires you to know the index of the item you want to remove.
# Create a sample list
fruits = ['apple', 'banana', 'cherry', 'date']
# Print the original list
print(fruits) # Output: ['apple', 'banana', 'cherry', 'date']
# Delete an element at index 1 (banana)
del fruits[1]
# Print the updated list
print(fruits) # Output: ['apple', 'cherry', 'date']
In this example, we create a list fruits
and then use the del
statement to remove the item at index 1. The output shows that the element 'banana'
has been successfully deleted.
Method 2: Using pop()
Function
Another way to delete an element is by using the pop()
function. This method also requires you to know the index of the item you want to remove.
# Create a sample list
fruits = ['apple', 'banana', 'cherry', 'date']
# Print the original list
print(fruits) # Output: ['apple', 'banana', 'cherry', 'date']
# Delete an element at index 1 (banana)
fruits.pop(1)
# Print the updated list
print(fruits) # Output: ['apple', 'cherry', 'date']
In this example, we use the pop()
function to remove the item at index 1. The output shows that the element 'banana'
has been successfully deleted.
Method 3: Using List Comprehension
You can also delete elements using list comprehension. This method requires you to know the value of the item you want to remove.
# Create a sample list
fruits = ['apple', 'banana', 'cherry', 'date']
# Print the original list
print(fruits) # Output: ['apple', 'banana', 'cherry', 'date']
# Delete all occurrences of 'banana'
fruits = [fruit for fruit in fruits if fruit != 'banana']
# Print the updated list
print(fruits) # Output: ['apple', 'cherry', 'date']
In this example, we use list comprehension to create a new list that excludes all occurrences of 'banana'
. The output shows that the element 'banana'
has been successfully deleted.
Conclusion
Deleting an element from a list in Python can be achieved using various methods and functions. Whether you’re using the del
statement, pop()
function, or list comprehension, the process is straightforward and easy to follow.