python - How to remove strings from list permanently? -
filelist = ['a.txt', 'b.pdf','c.exe','d.pdf','e.mp3'] extension = '.pdf' in filelist: if extension in i: print >>> b.pdf d.pdf >>>
the script prints out list want... how script alter filelist
read:
filelist = ['b.pdf', 'd.pdf']
???
i tried...
for in filelist: if extension not in i:
followed by...
del i, filelist.pop, filelist.remove, etc
but filelist
never permanently changes.
certain list operations not efficient. insert
, remove
random locations couple o(n).
removing items list iterating for
loop way introduce bugs items following removed ones skipped.
it turns out more efficient create new list filtering out undesired items
file_list = ['a.txt', 'b.pdf','c.exe','d.pdf','e.mp3'] extension = '.pdf' new_list = [x x in file_list if x.endswith(extension)]
notice changed logic use endswith
prevent inadvertent matches in filename path
Comments
Post a Comment