What Is Difference Between Del, Remove and Pop on Python Lists?
In python del is a keyword and remove(), pop() are in-built methods. The purpose of these three are same but the behavior is different remove() method delete values or object from the list using value and del and pop() deletes values or object from the list using an index. Show del Keyword:The del keyword delete any variable, list of values from a list. Syntax: del list_name[index] # To delete single value del list_name # To delete whole listExample: Python3
Output: [1, 2, 2, 3, 4, 5] [1, 2, 2, 3, 4] [2, 2, 3, 4] remove() Method:The remove() method removes the first matching value from the list. Syntax: list_name.remove(value)Example: Python3
Output: [1, 2, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 2, 3, 4]pop() Method:The pop() method like del deletes value at a particular index. But pop() method returns deleted value from the list. Syntax: list_name.pop(index)Example: Python3
Output: del V/S remove() the V/Spop()
Article Tags : Python Technical Scripter python-list Technical Scripter 2020 Practice Tags : python-list Difference between del, remove and pop on listsIn this article, we will learn the difference between the del, remove, and pop functions of a list in Python. We will use these built-in functions and discuss the difference with examples. Let's first have a quick look over what is a list in Python. remove()Thelist.remove(element)method removes the first occurrence of theelementfrom an existinglist. It does not, however, remove all occurrences of the element in the list! Syntax: list.remove(value) Example: In the below list the element 2 is deleted from the list. But another occurrence of 2 is still in place. li = [3, 5, 7, 2, 6, 4, 8, 2] li.remove(2) print(li) # [3, 5, 7, 6, 4, 8, 2]
If you specify a value that is not present in the list, Python raises ValueError. li = [3, 5, 7, 2, 6, 4, 8, 2] li.remove(82) print(li) # ValueError: list.remove(x): x not in listComplexity Analysis: The computational complexity when removing an element x from the list of n elements using the remove() method is O(n). Case 1: To delete the first element from a list of 10000 elements using remove() Note thatlist(range(10000)) generates a list with numbers 0 to 9999 something like [0,1,2,3,4,.......9999]. Case 2: To delete an element ‘5000‘ from the list of 10000 elements using remove(). Case 3: To delete the last element from a list of 100 elements using remove(). What is the difference between del, remove and pop on lists in python ?Object Oriented ProgrammingProgrammingPython It does't matter how many lines of code you write in a program. When you want to remove or delete any elements from the Python list, you have to think about the difference between remove, deland popin Python List and which one to use remove: remove() removes the first matching value or object, not a specific indexing. lets say list.remove(value) |