Computer Science
What's the purpose of the del operator and pop method? Try deleting a slice.
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()
Related Questions
What are list slices? What for can you use them?
How are the statements lst = lst + 3 and lst += [3] different, where lst is a list? Explain.
How are the statements lst += "xy" and lst = lst + "xy" different, where lst is a list? Explain.
What does each of the following expressions evaluate to? Suppose that L is the list
["These", ["are", "a", "few", "words"], "that", "we", "will", "use"].- L[1][0::2]
- "a" in L[1][0]
- L[:1] + L[1]
- L[2::2]
- L[2][2] in L[1]