i have item in a dictionary that needs to be deleted. which way is more pythonic?
del mydict['deleteme']
mydict.pop('deleteme')
i like the 2nd form because i can use it with a 2nd argument in cases where the item to be deleted may not actually be in the dictionary.
pop returns the item being 'deleted'
del does not
so proper answer is 'It depends on context'
so if i don't need the item i should use del instead of doing .pop without an assignment?
That's what I'd do, but that doesn't necessarily mean it's the best way. Seems to me returning a value would take some extra clock cycles .
yeah, even if the return value is ignore, it would be at least making it available. there is a "__delitem__" method for a dictionary. that might be intended for del.
.pop
is slightly slower than
del
(Python 3.6.3, GCC 4.8.5 linux):
Quote:python -m timeit "d = {'s':1 }; d.pop('s')"
Output:
1000000 loops, best of 3: 0.236 usec per loop
Quote:python -m timeit "d = {'s':1 }; del d['s']"
Output:
10000000 loops, best of 3: 0.14 usec per loop
i need to be sure i don't replace instance of this where the returned value is used or a 2nd argument is given. in the latter, even when the return value is ignored, it ignores the case where the item is not actually present, avoiding raising an except, effectively operating as "be sure this item is not present".
results are similar in python3.