Are these two for loops the same efficient in python?
Question:
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.
Answers:
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.
list(d)
are an Iterable
. What you’re doing is requesting access directly to that iterator component, and then moving the pointer that it’s behind it on every loop run.
Note that the for loop
is almost a syntactic sugar for iter.__next__()
, which gives you a mutable shared reference to an item inside the continer on every call.
But when you’re assigning it to your keys
variable, you’re copying the whole content on list(d)
call to some memory location, so yes, assigning it could be more expensive depending on how big is the content to copy.
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.
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.
list(d)
are an Iterable
. What you’re doing is requesting access directly to that iterator component, and then moving the pointer that it’s behind it on every loop run.
Note that the for loop
is almost a syntactic sugar for iter.__next__()
, which gives you a mutable shared reference to an item inside the continer on every call.
But when you’re assigning it to your keys
variable, you’re copying the whole content on list(d)
call to some memory location, so yes, assigning it could be more expensive depending on how big is the content to copy.