I am trying to populate a list called images with files that have the extensions '.png', '.jpg' or 'jpeg' in a one line for loop. I tried this by using the logical or operator but that only resulted in an empty list.
images = [i for i in os.listdir('.') if i[-4:] == ('.png' or '.jpg' or 'jpeg')]
How do I check to see if '.png', '.jpg' or 'jpeg' are the last 4 characters of the file while keeping it all in a one line for loop?
Using
oris a boolean expression which checks if any value in the expression evaluates toTrue.evaluates if
i[-4:]is equal to:which checks if each value is
Trueand returns the firstTruevalue or the last value if there are noTruevalues. In this case they all evaluate toTrueas only empty strings evaluate toFalseso'.png'is the result of the expression.You can fix this by doing
Or a better way