JavaScript
x
10
10
1
d = {'a':1, 'b':2, 'c':3}
2
3
keys = list(d)
4
5
for key in keys:
6
print(key)
7
8
for key in list(d):
9
print(key)
10
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:
JavaScript
1
9
1
d = {'a':1, 'b':2, 'c':3}
2
3
def _list(*args, **kwargs):
4
print("Calling list!")
5
return list(*args, **kwargs)
6
7
for key in _list(d):
8
print(key)
9
And the output is
JavaScript
1
5
1
Calling list!
2
a
3
b
4
c
5
It seems that list(d)
is only called once, so there’s no performance difference.