The fact is that after deleting elements from the beginning of the list, the indices of the remaining elements change and its length decreases, therefore in the end you are trying to access elements outside the list. The correct solution is to remove not from the beginning, but from the end:
def modify_list(n): s = "" for i in range(len(n)): if n[i] % 2 == 0: n[i] = n[i] // 2 elif n[i] % 2 > 0: s += str(i) for j in reversed(s): b = int(j) del n[b] return n les = [1,2,3,4,5,6,7,8,9] print(modify_list(les))
If you look deeper, then storing indexes in a row is wrong, and for this it is better to use the list:
def modify_list(n): s = [] for i in range(len(n)): if n[i] % 2 == 0: n[i] = n[i] // 2 elif n[i] % 2 > 0: s.append(i) for j in reversed(s): del n[j] return n les = [1,2,3,4,5,6,7,8,9] print(modify_list(les))
We optimize it even more. The condition n[i] % 2 > 0 will always be fulfilled, so it can be excluded. And further we will use the generator of lists:
def modify_list(n): return [x // 2 for x in n if x % 2 == 0] les = [1,2,3,4,5,6,7,8,9] print(modify_list(les))
Note that the last code does not modify the original list, but creates a new one.
list.remove(obj)in this case. - mkkik