I
I
Ilya2021-08-06 13:51:52
Python
Ilya, 2021-08-06 13:51:52

How to fix the code to solve the problem?

Connoisseurs, tell me, please, where is my mistake in the code...
The essence of the task: Write a function modify_list(l), which takes a list of integers as input, removes all odd values ​​from it, and divides the even ones by two. The function should not perform input/output of information, it only needs to change the passed list.
My code:

def modify_list(l):
    for i in range(len(l)):
        if i % 2 == 1:
            l.remove(l[i])
        elif i % 2 == 0:
            i = l.append(l[i//2])
    return (l)

Please do not send other solutions, but correct this particular fragment.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-08-06
@Vindicar

You need to be careful when iterating over the indexes of a list and modifying it at the same time. If you have deleted an element, the indices of the subsequent ones will "move" to the left, to zero, and with a normal enumeration, you will skip the element immediately after the deleted one.
A good solution is to iterate over the elements in reverse order, then the indexes of already processed elements will "move out".

for i in range(len(l)-1, -1, -1):
  if l[i] % 2 == 0:
    l[i] = l[i] / 2
  else:
    del l[i]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question