d = {'a':1, 'b':2, 'c':3} keys = list(d) for key in keys: print(key) for key in list(d): print(key)
My question is for the 2nd for loop, is ‘list(d)’ executed multiple times, or only once? If it is executed only once, it’s more compact.
Advertisement
Answer
Here’s a simple test:
d = {'a':1, 'b':2, 'c':3} def _list(*args, **kwargs): print("Calling list!") return list(*args, **kwargs) for key in _list(d): print(key)
And the output is
Calling list! a b c
It seems that list(d)
is only called once, so there’s no performance difference.