0

What is the difference between remove and del ? I read that remove deletes the first occurrence, while del removes the item at a specified index, but I tried to use index with remove and it worked so, what's the actual difference and the actual use???

>>> list=[1,2,3,4]
... list.remove(list[0])
... print(list)
[2, 3, 4]
>>> list=[1,2,3,4]
... list.remove(1)
... print(list)
[2, 3, 4]
>>> list=[1,2,3,4]
... del(list[0])
... print(list)
[2, 3, 4]
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Samar Hatem
  • 11
  • 1
  • 3
  • In this case there will *be no difference*, since the items in the list are unique. Of course, if you don't know the index, `.remove` will be more useful. But try it with `l = [1,2,3,4,1]` and `l.remove(l[4])` and `del l[4]` – juanpa.arrivillaga Apr 19 '18 at 06:09
  • that helped me, thanks so much :) – Samar Hatem Apr 19 '18 at 06:16

2 Answers2

0

If you want to delete particular element whose index is unknown from the list use remove(element) and if you want to delete element at particular index use del(list[index]).

Vikas Satpute
  • 174
  • 2
  • 19
0

remove removes the first matching value

l=[1,2,3,4,5,6,2]

l.remove() will remove first occurance and modified list will be

[1,3,4,5,6,2]

but using del you can del last last as well

del l[-1]

I found more useful when want to remove multiple value:

l=[1,2,3,4,5,6,7]

now i want to remove from index 2 to 4

del l[2:5]
#[1, 2, 6, 7]
Roushan
  • 4,074
  • 3
  • 21
  • 38