Replace for loop with safer code