Simple example:
myList = [1, 2, 3, 4, 5]
for obj in myList:
obj += 1
print myList
prints
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
while:
myList = [1, 2, 3, 4, 5]
for index in range(0,len(myList)):
myList[index] += 1
print myList
prints
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6]
Conclusion:
- Lists can be modified in place using global list access Lists can
- List items can NOT be modified in place using the iterator object
All example code I can find uses the global list accessors to modify the list inplace.
Is it so evil to modify a list iterator?
in
for obj in myList:, in every iteration,objis a (shallow) copy of the element inmyList. So the change on theobjdoes nothing tomyList‘s elements.It’s different with the Perl
for my $obj (@myList) {}