I have the following simplest script

inp = input().split() print('inp', inp) l = [] for elem in inp: l.append(int(elem)) print('initial: ', l) for el in l: print(el) if el % 2 != 0: l.remove(el) print('after removing odd numbers: ', l) 

First input (string):

 1 2 3 4 5 6 7 

conclusion:

 inp ['1', '2', '3', '4', '5', '6', '7'] initial: [1, 2, 3, 4, 5, 6, 7] 1 3 5 7 after removing odd numbers: [2, 4, 6] 

Second input (string):

 10 8 5 3 1 

conclusion:

 inp ['10', '8', '5', '3', '1'] initial: [10, 8, 5, 3, 1] 10 8 5 1 after removing odd numbers: [10, 8, 3] 

Screenshot here .

1st I / O

1) Why does the script display only odd items? It must output all elements.


2nd I / O

1) Why is there no number 3 in the output, only 10, 8, 5 and 1?

2) And, therefore, why does the final list contain the number 3?

Thank you

    2 answers 2

    You go through the list of the cycle that you are changing. It is a bad idea. When you delete the current element in the loop from the list, inside the python the next element becomes implicitly current. And when the next iteration begins, the next element is taken again, thus one element slips.

    I will show clearly on this code:

     a = [1, 2, 3, 4, 5] for x in a: a.remove(x) 

    The first iteration before deletion is taken element with index 0:

     [1, 2, 3, 4, 5] ^ - текущий элемент 

    The first iteration after deletion (note that nobody will change the value of the variable x ):

     [2, 3, 4, 5] ^ 

    Oops, we implicitly changed the current item. Although the variable x still contains one, at index 0 there is already a completely different element.

    The second iteration takes an element with index 1:

     [2, 3, 4, 5] ^ 

    Oops! Slipped.


    How to treat?

    Never change the list you cycle through. For example, make a copy of it and run a loop on the copy:

     l_copy = l[:] for el in l_copy: print(el) if el % 2 != 0: l.remove(el) 

    For a better understanding of the work cycle is another example:

     a = [0, 0, 0, 0] i = 1 for x in a: a.insert(i, 7) print(x) i += 1 

    This code will first print 0, and then it will infinitely issue sevens :)

     a = [0, 1, 2, 3] i = 0 for x in a: a.insert(i, 7) print(x) i += 1 

    But there will be no sevens, but there will be endless zeros (we constantly shift it to the right with new sevens and it always turns out to be the next element in the index).

    • Thanks, now everything fell into place! - Artsiom Praneuski
    • бесконечно будет выдавать семёрки only if we have infinite memory - Andrio Skur

    Do not delete items while passing through the list. Use list inclusion to create a new list with items that satisfy the condition you need.

     a = [1, 2, 3, 4, 5] b = [el for el in a if el%2 == 0] print (b)