KnowledgeBoat Logo
|

Computer Science

What are the two ways to remove something from a list? How are they different ?

Python List Manipulation

2 Likes

Answer

The two ways to remove something from a list are:

  1. pop method — The syntax of pop method is List.pop(<index>).

  2. del statement — The syntax of del statement is

del list[<index>] # to remove element at index
del list[<start>:<stop>] # to remove elements in list slice

Difference

The difference between the pop() and del is that pop() method is used to remove single item from the list, not list slices whereas del statement is used to remove an individual item, or to remove all items identified by a slice.

Example

pop() method:

t1 = ['k', 'a', 'e', 'i', 'p', 'q', 'u']  
ele1 = t1.pop(0)
print(ele1)

Output — 'k'

del statement:

lst = [1, 2, 3, 4, 5]
del lst[2:4]
print(lst)

Output — [1, 2, 5]

Answered By

2 Likes


Related Questions