DEV Community

Keerti Sadana S
Keerti Sadana S

Posted on

PYTHON - DEL(), REMOVE() AND POP()

del():
-> del is a Python keyword used to delete items from a list by index or to remove the entire list.
-> With del, we can specify a single element by index or use slicing to delete a range of elements.

a = [1, 2, 3, 2, 3, 4, 5]
del a[3]
print(a)
a = [1, 2, 3, 2, 3, 4, 5]
del a[1:3]
print(a)
Enter fullscreen mode Exit fullscreen mode

Output:
[1, 2, 3, 3, 4, 5]
[1, 2, 3, 4, 5]

remove():
The remove() method removes the first matching value from the list. It requires the value we want to remove from list as its argument.

a = [1, 2, 3, 2, 3, 4, 5]
a.remove(3)
​print(a)
Enter fullscreen mode Exit fullscreen mode

Output:
[1, 2, 2, 3, 4, 5]

pop():
-> The pop() method removes and returns an element from the list.
-> By default, it removes the last element, but we can specify an index to remove an element at a particular position.

a = [1, 2, 3, 2, 3, 4, 5]
a.pop(3)
print(a)
Enter fullscreen mode Exit fullscreen mode

Output:
[1, 2, 3, 3, 4, 5]

del() VS remove() vs pop():

Top comments (0)