Important list methods for removing and replacing elements

Using the del keyword

Through this keyword, we can delete elements of a specific index

listx = [1,2,3,4,5,6,7]

del listx[2]

print(listx)

Using the pop keyword

This keyword will delete an element at a specific index and return the value

listx = [1,2,3,4,5,6,7]

x =  listx.pop(2)
print(x)
print(listx)

Using the remove keyword

This keyword will remove the first occurrence of the element to be removed.

listx = [1,2,3,4,5,6,7]

x =  listx.remove(2)
print(x)
print(listx)

Using list comprehension

listx = [1,2,3,4,5,6,7]

listx = [x for x in listx if x != 2]
print(listx)

Replacing elements in the list

listx = [1,2,3,4,5,6,7]

for i in range(len(listx)):
    if listx[i] ==2:
        listx[i] = 3
print(listx)