0

i found this code and i am just confused why are the even numbers retained in list x when the remove method is at the top of the for loop, i tried to print the list for each iteration and it shows the first iteration is 1, gets removed from x then appended to y, but the next iteration of i is now 3 not 2

x = [1,2,3,4,5,6,7,8,9,10]
y = []

for i in x:
    x.remove(i)
    if i%2 == 0:
        continue
    elif len(x) == 5:
        break
    y.append(i)
    
print(x) # output [2, 4, 6, 8, 10]
print(y) # output [1, 3, 5, 7]

adding print before the remove method

...
print(i)
print(x)
x.remove(i)
...

as you can see the next iteration is 3 not 2 when 2 is still in list x

1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
3
[2, 3, 4, 5, 6, 7, 8, 9, 10]   
5
[2, 4, 5, 6, 7, 8, 9, 10]      
7
[2, 4, 6, 7, 8, 9, 10]
9
[2, 4, 6, 8, 9, 10]
k1dr0ck
  • 1,043
  • 4
  • 13

1 Answers1

1

You are looking at code which modifies on the fly the list it is iterating on -- which isn't advised, and can be seen as sawing the branch you are sitting on. The behavior of that program depends on how the python interpreter implements iteration on an array.

A blind guess would be: it internally keeps an index of the cell it should inspect (0, then 1, then ...) and accesses x[index] at each step.
Since each iteration shifts the content of x, you see the behavior you describe : on the first iteration x[0] is 1, on the 2nd iteration x[1] is 3, etc ...


If your goal is to split that list into odd and even numbers, there are a number of other ways to do this:

x = [1,2,3,4,5,6,7,8,9,10]

odd = [n for n in x if n%2 == 1]
even = [n for n in x if n%2 == 0]

print(odd)
print(even)
LeGEC
  • 46,477
  • 5
  • 57
  • 104
  • as a beginner this was really confusing and disorienting :D – k1dr0ck Aug 31 '23 at 04:50
  • the question listed as duplicate has a [much more complete answer](https://stackoverflow.com/a/6260097/86072), in which a commenter points to the [python documentation](https://docs.python.org/3.9/reference/compound_stmts.html#the-for-statement) which actually has an [_explicit note_](https://docs.python.org/3.9/reference/compound_stmts.html#index-9) to describe this very behavior. – LeGEC Aug 31 '23 at 05:47