-2

Consider the following two pieces of code for popping keys from a dict:

  1. without list comprehension
    d = {'a': 1, 'b': 2, 'c': 3}   
    d.pop('a')
    d.pop('b')
  1. with list comprehension
    d = {'a': 1, 'b': 2, 'c': 3}
    [d.pop(key) for key in ['a', 'b']]

Which one will be faster and why?

Mehdi Mostafavi
  • 880
  • 1
  • 12
  • 25
Ulysses
  • 5,616
  • 7
  • 48
  • 84
  • 4
    Assuming you just want to remove the keys - a & b - first will be faster. Why do you think second will be faster when you are doing additional work? – lllrnr101 Apr 19 '21 at 06:32
  • 1
    Take a look at https://stackoverflow.com/a/67145260/14904573 to determine & analyse the performance of small segments by using timeit. – lllrnr101 Apr 19 '21 at 06:34
  • 2
    The first will be the preferable way of doing it.. in the latter intermediate list is thrown away after it is created which is considered [`very anti-Pythonic`](https://stackoverflow.com/q/5753597/4985099) – sushanth Apr 19 '21 at 06:36
  • 2
    There is no need to call the `pop` method if you are going to throw away its returning value. Use `del d['a']` instead. – blhsing Apr 19 '21 at 06:43
  • Why would the list comprehension ever be faster? It requires more work (creating a list). Also, just the looping requires more work, since it requires iteration, which has overhead. More importantly, though, you should be profiling this yourself. – juanpa.arrivillaga Apr 19 '21 at 06:56
  • @sushanth perhaps even more fundamentally, you shouldn't be mixing a functional, declarative construct like list-comprehensions to implement a series of side-effects, even leaving out the unnecessary list – juanpa.arrivillaga Apr 19 '21 at 06:57
  • Please [edit] your question to make it answerable without merely repeating the question itself. It is trivial to just *test* which one is faster, and the question already explains why – because the fast one is *without* and the slow one is *with* additional operations. That said, the two are not at all equivalent – if this question is not just for curiosity, consider to *shortly* outline the usecase to avoid an XY problem. – MisterMiyagi Apr 19 '21 at 08:00

1 Answers1

0
import timeit
code_to_test1 =  """d = {'a': 1, 'b': 2, 'c': 3}   
d.pop('a')
d.pop('b')"""
code_to_test2 =  """d = {'a': 1, 'b': 2, 'c': 3}
[d.pop(key) for key in ['a', 'b']]"""
elapsed_time1 = timeit.timeit(code_to_test1, number=5000)
elapsed_time2 = timeit.timeit(code_to_test2, number=5000)
print(elapsed_time1,elapsed_time2)

Output(s):

0.0008224000000000009 0.0017937999999999982
0.000853600000000003 0.0018411999999999942
0.0008063000000000028 0.002663699999999998

So as you see, the first one is faster than the second code because, in the second one, you iterating in a list.

Mehdi Mostafavi
  • 880
  • 1
  • 12
  • 25