1

I would like to iterate over the elements of a list, and delete the wrong ones. First, lets check all elements:

tikzFiles=['keepme.tikz','inputs.tex','bla1.bat','bla2.tex','bla3.py']

for sFile in tikzFiles:
    print(sFile)
    print(sFile.endswith('.tikz'))

This leads to the expected result:

keepme.tikz
True
inputs.tex
False
bla1.bat
False
bla2.tex
False
bla3.py
False

Two more lines, however,

for sFile in tikzFiles:
    print(sFile)
    print(sFile.endswith('.tikz'))
    if not sFile.endswith('.tikz'):
        tikzFiles.remove(sFile)

let the for-loop ignore the elements 'bla1.bat' and 'bla3.py':

keepme.tikz
True
inputs.tex
False
bla2.tex
False
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
bbk
  • 45
  • 4
  • 3
    You're modifying the list whilst looping so the position that the iterator is using is no longer referencing the original list – EdChum May 13 '15 at 09:33

1 Answers1

3

Use list comprehension to create a new list with only the elements you want, like this

>>> tikzFiles = ['keepme.tikz', 'inputs.tex', 'bla1.bat', 'bla2.tex', 'bla3.py']
>>> [file for file in tikzFiles if file.endswith('.tikz')]
['keepme.tikz']

Note: More often, removing an element from a collection while you iterate it, is a bad idea. Check this answer to know more about what is actually going on at runtime.

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497