python loop refactor