Python - For Loop To Remove List Items By File Extension
I must be missing something fundamental as it's been a while since I've used python. I have a simple function that I'd like to return a list of .jpg's from a directory, but it is r
Solution 1:
You should not change the list while iterating over it. That will screw the indexing.
Use list comprehension:
>>> pictures = ['abc.jpg', 'abc.gif', 'abc.png', 'cde.jpg']
>>> [pic for pic in pictures if pic.endswith('jpg')]
['abc.jpg', 'cde.jpg']
Or filter()
with lambda()
:
>>> filter(lambda pic: pic.endswith('jpg'), pictures)
['abc.jpg', 'cde.jpg']
Post a Comment for "Python - For Loop To Remove List Items By File Extension"