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 s: b = int(j) del n[b] return n les = [1,2,3,4,5,6,7,8,9] print(modify_list(les)) 

error: func.py ", line 10, in modify_list del n [b] IndexError: list assignment index out of range

  • This happens because you have defined the indices of odd elements on the full list, and you are trying to delete the elements by these indices already in the modified one. It is better to use list.remove(obj) in this case. - mkkik

1 answer 1

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.