I can't fix the code for the task on stepik.org

The task sounds like this:"Write a function modify_list (l), which takes as input a list of integers, removes all odd values from it, and divides the even ones completely by two. The function should not return anything, it only needs to change the passed list, for example:

lst = [1, 2, 3, 4, 5, 6]
print(modify_list(lst))  # None
print(lst)               # [1, 2, 3]
modify_list(lst)
print(lst)               # [1]

lst = [10, 5, 8, 3]
modify_list(lst)
print(lst)               # [5, 4]

The function must not perform input / output of information. "

My code looks like this (it may be very crooked, but I'm still learning :)):

def modify_list(l):
    for i in l:
        if i%2==1:
            l.remove(i)
    L=[]
    for i in l:
        if len(l)!=0:
            i=i//2
            L+=[i]
    l.clear()
    l.extend(L)
    return(l)

The code works fine when in the list contains the values from the example (lst = [1, 2, 3, 4, 5, 6] and lst = [10, 5, 8, 3]), but when the list contains only odd values, the program, as required, removes all odd numbers, but for some reason leaves one or two numbers. For example, when the list contains numbers [1, 13, 7, 3], then the program at the stage of checking the parity or odd number leaves [13], and, accordingly, in the output gives the number [6].

Comrades, could you please help me, a silly novice programmer, can you tell me how to solve this embarrassment?

Author: MaxU, 2020-08-19

2 answers

That's what I decided:

def modify_list(l):
    i, n = 0, len(l)
    while i < n:
        if l[i] % 2:
            l.pop(i)
            n -= 1
        else:
            l[i] = l[i] // 2
            i += 1

But it is readable and beautiful

 1
Author: Igorok, 2020-08-19 10:36:43

This question is asked here almost every day. You can't delete items from the list that you iterate on - the iteration of items breaks down. The simplest solution here is to iterate in for from a copy of the list obtained through l[:], either through l.copy(), or through list(l).

But in general, the pythonic way is not to modify an existing list, but to create a new one using filtering, list inclusion, etc. Then there will definitely be no problems. Well unless your list doesn't giant, and there are few deletions/changes - then it is acceptable to modify the existing list "in place" (inplace).

 1
Author: CrazyElf, 2020-08-19 10:41:23