[Tutor] Help return a pattern from list

Alan Gauld alan.gauld at btinternet.com
Tue Jul 6 01:19:02 CEST 2010

"Shashwat Anand" <anand.shashwat at gmail.com> wrote

>>>> list =
> ["something1.mp3","something2.mp3","something4.pdf","something5.odt"]
>>>> [i for i in list if i[-4:] == '.mp3']
> ['something1.mp3', 'something2.mp3']

Or even easier:

>>> [s for s in list if s.endswith('.mp3')]

But for the specific case of file extensions the os.path.splitext() is
a better solution.

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list