Deleting Elements of List
As we know that lists are mutable, we can delete elements within it. There are several ways to delete elements from a list. Like, if we know the index of the element to be deleted, we can use pop
function,
list1 = [12,23,43,[2,4,5], 2, 4,5]
list1.pop(3)
It deletes the element at index 3
.
So, what is the sum of all elements for the resulting list?
pop
modifies the list and returns the element that was removed. If we don't provide an index, it deletes and returns the last element.
If we do not want the deleted value, we can use the del
operator which deletes the element but doesn't return anything.
list2 = ['cloudx', 'lab', 'provides', 'cloud', 'lab']
del list2[1]
print(list2)
It prints ['cloudx', 'provides', 'cloud', 'lab']
And, if we know the element that needs to be removed, we can use remove
,
list2.remove('lab')
The return value from remove
is None
.
To remove more than one element, we can use del
with a slice index:
list2 = ['cloudx', 'lab', 'provides', 'cloud', 'lab']
del list2[:]
What is the length of the resulting list?
Loading comments...