'Most efficient way to write for loop equations for basic formulas in general coding

I'm learning coding and a quick probably basic question is, when calculating formulas using a for loop, is it more efficient to minimise the number of steps by packing everything into one equation, or to minimise the number of actual computations by moving repeated steps outside the loop? I've made a simple example for calculating a mean in python:

a = example 1D array
mean = 0
n = len(a)

for i in range(n):
     mean += mean / n

or

for i in range(n):
     mean += mean
mean /= n

My intuition says the second scenario would be quicker, I'm sure it's negligible though. Thank you



Solution 1:[1]

In your specific example, the second snippet is faster, because you repeat only the additions and do the division only once; in the first snippet, each iteration of the loop involves both a division and an addition. But that's a feature of this particular example, and I don't think it can be generalised such that it's always faster to take as much as possible out of the loop.

By the way, your first snippet is wrong; you'd want mean += i / n (in each iteration, you add the nth fraction of the current number to your overall mean).

Solution 2:[2]

Where Python has built-in functions that could obviate the need for an explicit loop, then they are likely to give better performance. For example:

def calc_mean(lst): # input is a list of numbers
  total = 0
  for v in lst:
    total += v
  return total / len(lst)

That's a simple iterative approach to calculate an arithmetic mean.

But...

def calc_mean(lst):
  return sum(lst) / len(lst)

...is likely to be faster.

This is not meant to show a definitive method for calculating a mean but just to emphasise the potential advantage(s) of using built-ins.

EDIT: I've timed this

I have a list of 1,000 pseudo-random numbers. I call each of these functions 25,000 times. The first function took 0.83s the second took 0.09s. QED

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Schnitte
Solution 2