I know it's not recommended to change a list while iterating over it, but I'm curious as to why the two different codes below give different results:
numbers = [1,2]
for i in numbers :
if len(numbers)<3:
numbers.append(3)
print(i)
and
numbers = [1,2]
for i in numbers :
if len(numbers)<3:
numbers = [1,2,3]
print(i)
The first code outputs 1,2,3 and the seconde code outputs only 1,2.
I would expect both code to behave exactly the same as in both cases I'm modifying the content of the list I'm ranging over.
CodePudding user response:
By writing numbers = [1, 2, 3]
, you did not change the content of the pre-existing list numbers
to [1, 2, 3]
, you assigned [1, 2, 3]
to a new variable.
You need to write numbers[:] = [1, 2, 3]
to keep the old list alive and change its content. That will print 1, 2, 3
as you expect.