Computer Science

What's the purpose of the del operator and pop method? Try deleting a slice.

Python List Manipulation

30 Likes

Answer

The del statement is used to remove an individual element or elements identified by a slice. It can also be used to delete all elements of the list along with the list object. For example,

lst = [1, 2, 3, 4, 5, 6, 7, 8]
del lst[1]   # delete element at index 1
del lst[2:5] # delete elements from index 2 to 4
del lst # delete complete list 

pop() method is used to remove a single element from the given position in the list and return it. If no index is specified, pop() removes and returns the last element in the list. For example,

lst = [1, 2, 3, 4, 5, 6, 7, 8]

# removes element at  
# index 1 i.e. 2 from 
# the list and stores 
# in variable a
a = pop(1)

# removes the last element 
# i.e. 8 from the list and
# stores in variable b
b = pop()

Answered By

16 Likes


Related Questions