





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
Delete items from Sorted list
Deleting items from a Sorted list:
We can delete items from sorted listed in Python using the following methods
- Pop- delete items based on index of elements
- Remove- removes the particular item
- Del- deletes group of elements
- Clear- clears an entire list
We can use any of these according to the application. Let’s see how each function works for a sorted list and lastly, we will see a method to delete an item manually.

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.
Code#1:
#rishikesh
#delete item in a sorted list
#python Program
#python Program
ar=[1,4,2,5]
#sorting the array
ar.sort()
print(‘Popped element:’,ar.pop())
print(‘After popping element list-‘ , ar)
Output :
Popped element: 5
After popping element list- [1, 2, 4]
- Pop operation Takes O(1) time, to delete the element from the list but it deletes the last element from the list.
Remove :
- Remove deletes the item that is passed as argument for remove function. It removes first occurrence of that item.
Code #2
#rishikesh
#delete item in a sorted list
#python Program
ar=[1,4,2,5]
ar.remove(4)
print(‘After Removing a element from list-‘ , ar)
Output :
After Removing a element from list- [1, 2, 5]
- Remove Takes O(n) time to delete a item from the list.
Clear :
- Clear is used to delete entire list at same time.
Del :
- Del() function deletes group of elements of list at once by using slicing. del(x[:]) this will delete entire list
We can delete a item from list manually .
Code #3:
#prepInsta
#rishikesh
#delete item in a sorted list
#python Program
x=[1,2,3,56,3,3,22]
x.sort()
del(x[1:3])
print(“List after deleting group of elements: “,x)
#deleting manually 56
a=22
for i in range(len(x)):
if(x[i]<a):
pass
elif(x[i]==a):
pass
elif(x[i]>a):
x[i-1]=x[i]
x.pop()
print(‘After deleting a element :’,x)
#deleting the whole list
x.clear()
print(‘After clear function:’,x)
Output :
List after deleting group of elements: [1, 3, 3, 22, 56]
After deleting a element : [1, 3, 3, 56]
After clear function: []
- These are the various method to delete items from sorted list in python.
Login/Signup to comment