How to delete or remove elements from a list?
remove() – Removes an item from the list
pop() – Removes and returns an element at the given index
clear() – Removes all items from the list
del() : to remove an element. We can delete one or more items from a list using the keyword del. It can even delete the list entirely.
Example:2
n=[0,1,2,3,4,5,6,7,8,9,10]
n.remove(4)
print(n)
#[0, 1, 2, 3, 5, 6, 7, 8, 9, 10]
n.remove(5)
print(n)
#[0, 1, 2, 3, 6, 7, 8, 9, 10]
n.remove(9)
print(n)
#[0, 1, 2, 3, 6, 7, 8, 10]
n.remove(10)
print(n)
#[0, 1, 2, 3, 6, 7, 8]
#n.remove(10) #error will be displayed as element is not present
#print(n)
remove() :
Removes an item from the list by using value of item/element
Note:
In case of remove() function if the element is not present an error gets generated
n1=[‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’]
print(n1)
output:
[‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]
n1.remove(‘m’)
print(n1)
output:
[‘c’, ‘o’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]
n1.remove(‘p’)
print(n1)
output:
[‘c’, ‘o’, ‘u’, ‘t’, ‘e’, ‘r’]
n1.remove(‘t’)
print(n1)
output:
[‘c’, ‘o’, ‘u’, ‘e’, ‘r’]
Example:
n=[0,1,2,3,4,5,6,7,8,9,10]
n.remove(4)
print(n)
Output:
[0, 1, 2, 3, 5, 6, 7, 8, 9, 10]
n.remove(5)
print(n)
Output:
[0, 1, 2, 3, 6, 7, 8, 9, 10]
n.remove(9)
print(n)
Output:
[0, 1, 2, 3, 6, 7, 8, 10]
n.remove(10)
print(n)
Output:
[0, 1, 2, 3, 6, 7, 8]
n.remove(10) #error will be displayed as element is not present
print(n)