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

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -