Search code examples
pythonpython-2.7ends-with

Is it possible to reduce function to one single line?


I wrote an image checker, now I wonder how can I reduce the number of lines in this function to (if possible) one single line.

myFiles = ['image94.jpg','image95.png','image96.jpg','movie97.mov']
suff = ('.jpg', '.png')

# Check if files are images
def checker(suff):
    imageFiles = []
    for files in myFiles:
        if files.endswith(suff):
            imageFiles.append(files)
    return imageFiles

if checker(suff): print checker(suff)

Solution

  • Use a conditional list comprehension:

    [filename for filename in myFiles if filename.endswith(suff)]