Deleting Items from the List in Python

how to delete an element in python

Deleting Items from the List

In Python, you can delete items from a list using various methods and operations. We can use any of these according to the application. Lets see how each function works.

Deleting Items from the List 

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 
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.

Run
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.

Run
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 

Run
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 

Run
x=[1,2,3,56,3,3,22]
x.clear() 
print("List after Deleting entire list ",x)
List after Deleting entire list []

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription