Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Deleting items from the list in Python

how to delete an element in python

Deleting items

In python we can delete items using following methods

  • Pop-  delete items based on index of elements
  • Remove- removes particular item 
  • Del- deletes group of elements
  • Clear- clears entire list 

We can use any of these according to the application. Lets see how each function works.

Deleting items from the list in Python

Pop:

Pop deletes based on index of the items. If index not given then it take last index of list in default . We can store the deleted item into another variable.

list1=[“channa”,“milk”,“bread”,“apples”,“salt”,“sugar”,“coconut”,“salt”]
y=list1.pop(0)
print(“Popped element :”,y) 
print(“List after poping an element at particular index\n,list1)
Popped element : channa
List after poping an element at particular index
['milk', 'bread', 'apples', 'salt', 'sugar', 'coconut', 'salt']

Remove :

Remove deletes the item that is passed as argument for remove function. It removes first occurrence of that item.

list1=[“channa”,“milk”,“bread”,“apples”,“salt”,“sugar”,“coconut”,“salt”]

list1.remove(“salt”)
print(“List after removing an specific element\n,list1) 
List after removing an specific element
['channa', 'milk', 'bread', 'apples', 'sugar', 'coconut', 'salt']

Del :

Del() function deletes group of elements of list at once by using slicing. del(x[:]) this will delete entire list 

x=[1,2,3,56,3,3,22]
del(x[1:3])
print(“List after deleting group of elements\n,x)
List after deleting group of elements
[1, 56, 3, 3, 22]

Clear :

Clear is used to delete entire list at same time 

x=[1,2,3,56,3,3,22]

x.clear() 
print(“List after Deleting entire list “,x)
List after Deleting entire list []