Delete Items from Sorted List
Deleting Items from a Sorted List:
The clear(), pop(), and remove() functions in Python can be used to eliminate entries from a list. The del statement also allows you to delete things by specifying a position or range with an index or slice.
Delete Items from 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:
#delete item in a sorted list #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:
#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:
#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): 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.
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
Login/Signup to comment