Your problem stems from the fact that you are not looping over a different list, like you want to be. You want to avoid deleting something from a list while looping over it, which is why you created a new list with numbers_buf = numbers
However, note that no new list was created:
In [73]: numbers = list(range(10))
In [74]: numbers
Out[74]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [75]: id(numbers)
Out[75]: 4469310792
In [76]: numbers_buf = numbers
In [77]: id(numbers)
Out[77]: 4469310792
In [78]: id(numbers_buf)
Out[78]: 4469310792
In [79]: id(numbers_buf) == id(numbers)
Out[79]: True
In [80]: numbers
Out[80]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [81]: numbers_buf
Out[81]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [82]: numbers.append(10)
In [83]: numbers_buf
Out[83]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Notice in the end, when I append 10
to numbers
, it gets appended to numbers_buf
as well. This is because python doesn't create a new list with numbers in them when you do numbers_buf = numbers
; It simply creates the name numbers_buf
and makes it point to the exact same structure that numbers
points to (this is what all that id(numbers)
stuff shows). You could solve this problem as follows:
In [84]: numbers_buf_new = numbers[:]
In [85]: id(numbers_buf_new)
Out[85]: 4469329032
In [86]: id(numbers_buf_new) == id(numbers)
Out[86]: False
In [87]: numbers
Out[87]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [88]: numbers_buf_new
Out[88]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [89]: numbers.append(11)
In [90]: numbers
Out[90]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
In [91]: numbers_buf_new
Out[91]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]