Is iterating over some_dict.items() as efficient as iterating over a list of the same items in CPython?
Is iterating over some_dict.items() as efficient as iterating over a list of the same
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It depends on which version of Python you’re using. In Python 2,
some_dict.items()creates a new list, which takes up some additional time and uses up additional memory. On the other hand, once the list is created, it’s a list, and so should have identical performance characteristics after the overhead of list creation is complete.In Python 3,
some_dict.items()creates a view object instead of a list, and I anticipate that creating and iterating overitems()would be faster than in Python 2, since nothing has to be copied. But I also anticipate that iterating over an already-created view would be a bit slower than iterating over an already-created list, because dictionary data is stored somewhat sparsely, and I believe there’s no good way for python to avoid iterating over every bin in the dictionary — even the empty ones.In Python 2, some timings confirm my intuitions:
Iterating over the
itemsis roughly twice as slow. Usingiteritemsis a tad bit faster…But iterating over the list itself is basically the same as iterating over any other list:
Python 3 can create and iterate over
itemsfaster than Python 2 can (compare to 57.3 us above):But the time to create a view is negligable; it is actually slower to iterate over than a list.
This means that in Python 3, if you want to iterate many times over the items in a dictionary, and performance is critical, you can get a 30% speedup by caching the view as a list.