How to delete element from list in python
In the python list we can delete an element by using three methods.
Delete element from list in python
1. pop()
We can use pop() function to remove item from list by index.
color = [ ‘Red’, ‘Green’, ‘Yellow’, ‘Black’ ]
color.pop(2)
print(color)
Output
[ ‘Red’, ‘Green’, ‘Black’ ]
If we do not pass the index in the pop() function then it will remove the last elements from the list.
color = [ ‘Red’, ‘Green’, ‘Yellow’, ‘Black’ ]
color.pop()
print(color)
Output
[ ‘Red’, ‘Green’, ‘Yellow’ ]
2. remove()
We can delete an element by using remove() function.
color = [ ‘Red’, ‘Green’, ‘Yellow’, ‘Black’ ]
print(color)
Output
color = [ ‘Red’, ‘Yellow’, ‘Black’ ]
3. del()
We can also use the del() function to remove elements from the python list.
color = [ ‘Red’, ‘Green’, ‘Yellow’, ‘Black’ ]
color.del(3)
Output
color = [ ‘Red’, ‘Green’, ‘Yellow’ ]
To remove multiple elements from the python list we can use del() function
color = [ ‘Red’, ‘Green’, ‘Yellow’, ‘Black’, ‘Pink’ ]
del color[ 1:3]
print(color)
Output
[ ‘Red’, ‘Black’, ‘Pink’ ]
Important Links: Informatics Practices
What is Python List
Characteristics of Python List
How to Create Python List
How to Traverse a list in Python
How to Manipulate list in Python
How to Modify multiple elements in Python list
Slicing in Python List
Built in function of Python List