Skip to content
Advertisement

Are these two for loops the same efficient in python?

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement