+ 1
What is the difference between del and remove() on lists?
del and remove() have the same funtions then why are there 2 words
3 Answers
+ 8
darius franklin ,
in short:
the difference is:
> `del list_name[index or slice]` is using an index number or a slice (integers) to delete a member / members from a list.
> to delete the last member of a list use: `del list_name[-1]`
> del can also delete an entire object / variable / list by using eg: `del list_name`
> remove(`value`) is a `list method` using a value to remove the first occurrence of a member from a list.
> to remove `bob` from a list: `list_name.remove("bob")`
+ 4
https://www.naukri.com/code360/library/what-is-the-difference-between-del-pop-and-remove-in-JUMP_LINK__&&__python__&&__JUMP_LINK
nums = [100,200,300,400,300]
print(nums)
# del removes elements by index or slice. Returns IndexError if the index is not found
del nums[1]
print(nums)
# .remove() removes element by value based on its first occurrence. Returns ValueError if the value is not found.
nums.remove(300)
print(nums)
# .pop() removes element by index. If no index is given, it removes the last item.Returns IndexError if the index is not found. It also returns the value of the removed element if assigned to a variable.
nums.pop(2)
print(nums)
+ 3
Slightly expanding the explanation about pop() method from Bob_Li.
As stated, "It also returns the value of the removed element if assigned to a variable."
nums = [100, 200, 300, 400, 300]
last_removed_num = nums.pop(1)
print(nums) # [100, 300, 400, 300]
print(last_removed_num) # 200