Q
Quinn Dunkan
Egbert Bouwman said:The answers you received don't tell you what you are doing wrong.I was trying to take a list of files in a directory and remove all but the ".dbf" files. I used the following to try to remove the items, but they would not remove. Any help would be greatly appreciated.
x = 0
for each in _dbases:
if each[-4:] <> ".dbf":
del each # also tried: del _dbases[x]
x = x + 1
I must be doing something wrong, but it acts as though it is....
If you replace 'del each' with 'print each' it works,
so it seems that you can not delete elements of a list you are
looping over. But I would like to know more about it as well.
egbert
"for each in ..." makes 'each' signify an element of _dbases. Then
"del each" makes 'each' no longer signify anything. So the above doesn't
really do anything at all. "del _dbases[x]" however does work, but
notice that if you delete element 3, element 4 becomes element 3, etc. Then
when 'x' is incremented to 4, you've skipped what used to be element 4 (which
is now element 3). In general, modifying a list while iterating over it is
more trouble than it's worth. Go with the listcomp solutions.