[python] Efficient way of having a function only execute once in a loop