A similar question has already been ask Cost of len() function here. However, this question looks at the cost of len
it self.
Suppose, I have a code that repea
Function calls in python are costly, so if you are 100% sure that the size of n_files
would not change when you are accessing its length from the variable, you can use the variable, if that is what is more readable for you as well.
An Example performance test for both accessing len(list)
and accessing from variable , gives the following result -
In [36]: l = list(range(100000))
In [37]: n_l = len(l)
In [40]: %timeit newn = len(l)
10000000 loops, best of 3: 92.8 ns per loop
In [41]: %timeit new_n = n_l
10000000 loops, best of 3: 33.1 ns per loop
Accessing the variable is always faster than using len()
.