2

If I want to remove a value from a list in python, is it proper to use delor can I just use pop() even though it returns the popped value?

I know the difference in how they can be used I just want to know specifically in terms of deleting from a list if I should be using del instead of pop() for everything.

list = [1, 2, 3]
del list[0]

vs.

list = [1, 2, 3]
list.pop(0)
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Excorpse
  • 29
  • 1
  • 3
  • 4
    Possibly a duplicate of: https://stackoverflow.com/questions/11520492/difference-between-del-remove-and-pop-on-lists There is no "correct way." If you need the `value` use pop, else use del. – Joseph Franciscus Dec 30 '18 at 04:47
  • What do you mean by "PROPER"? Use whichever one is needed in the situation in which it's being used, otherwise the code will be less clear, possibly less efficient, or could be even be considered misleading – martineau Dec 30 '18 at 08:24

1 Answers1

2

If you do not require the value, del is more correct in that it's easier for other readers to infer your intent (i.e. you just want to discard the value instead of using it for something).

However for all purposes that I can think of, they will act identically in your defined scenario. pop() obviously returns the value, but you are discarding it immediately.

There may be extremely minor performance / garbage collection benefits to using del over pop() but I am merely hypothesizing and have nothing to back that up. I am unsure of del's implementation but I can imagine potential implementations that'd be much faster than pop() due to not needing to return the removed value. Again, this is extremely minor and meaningless in most circumstances.

Kye
  • 4,279
  • 3
  • 21
  • 49