Thomas E Thomas E - 3 months ago 11
Python Question

Python for-loop with modification of the iterationlist

I have this .txt file:

king james version of the bible
the first book of moses called genesis


I use a python-script for statistics on .txt files, the file is read into the list
final_list
and then I execute this code (part of longer script):

for word in final_list:
output_list.append((word,final_list.count(word)))

final_list[:] = [x for x in final_list if x != word]
#DEBUGGING
print(len(final_list))
print(final_list)


My problem is that some of my list is not used by the for-loop, which I suspect form looking at the output:

12
['james', 'version', 'of', 'the', 'bible', 'the', 'first', 'book', 'of', 'moses', 'called', 'genesis']
11
['james', 'of', 'the', 'bible', 'the', 'first', 'book', 'of', 'moses', 'called', 'genesis']
9
['james', 'of', 'bible', 'first', 'book', 'of', 'moses', 'called', 'genesis']
8
['james', 'of', 'bible', 'book', 'of', 'moses', 'called', 'genesis']
6
['james', 'bible', 'book', 'moses', 'called', 'genesis']
5
['james', 'bible', 'book', 'moses', 'called']


This makes me wonder how the python for-loop actually works.

Answer

The trouble is that you're modifying the list. After the first iteration, Python's iterator stops looking at "position 0" in the list and moves to "position 1." You removed the element originally in position 0 (king), so the element that used to be in position 1 (james) is now in position 0, which means that when Python looks at the element in position 1, it sees the element that was originally in position 2 (version).

At the end, Python's iterator has moved to a position that is beyond the end of the list, so it quits in a manner you think is premature, even though that is precisely what you've asked it to do.

Comments