Move lambda range loops to function