-1

Python:

I have to use the length of a list which is the value for a key in a dictionary. I have to use this value in FOR loop. Is it better to fetch the length of the list associated with the key every time or fetch the length from a different dictionary which has the same keys?

I am using len() in the for loop as of now.

  • 1
    Welcome to stack overflow! Please [edit] your question to include a [mcve] showing sample input and expected output, and the code for what you've tried. Please also have a look at the documentation for the [timeit](https://docs.python.org/3/library/timeit.html) module, with which you can do code timing to answer your question – G. Anderson Dec 01 '22 at 23:54
  • 1
    `len()` is very fast - O(1) (https://stackoverflow.com/questions/1115313/cost-of-len-function) so I would not build a new data structure just to cache its answer. Use it each time you need it. Building a whole extra data structure, that would definitely be using more resources, and most likely slower. Just make sure you write your loop over `dict.items()`, not over the keys, so you don't unecessarily redo the key lookups inside the loop. – joanis Dec 01 '22 at 23:59

1 Answers1

0

len() is very fast - it runs in contant time (see Cost of len() function) so I would not build a new data structure just to cache its answer. Just use it each time you need it.

Building a whole extra data structure, that would definitely be using more resources, and most likely slower. Just make sure you write your loop over my_dict.items(), not over the keys, so you don't unnecessarily redo the key lookups inside the loop.

E.g., use something like this for efficient looping over your dict:

my_dict = <some dict where the values are lists>

for key, value in my_dict.items():
    # use key, value (your list) and len(value) (its length) as needed
joanis
  • 10,635
  • 14
  • 30
  • 40