newb question: file searching

Steve M sjmaster at gmail.com
Tue Aug 8 17:32:07 EDT 2006


jaysherby at gmail.com wrote:
>   I must ask, in the interest of learning, what is
>
> [file for file in files if file.endswith(extension)]
>
> actually doing?  I know that 'file' is a type, but what's with the set
> up and the brackets and all?

Other people explained the list comprehension, but you might be
confused about the unfortunate choice of 'file' as the name in this
example. 'file' is a built-in as you remarked. It is allowed, but a bad
idea, to use names that are the same as built-ins. Some people
characterize this as shadowing the built-in.

A similar, common case is when people use the name 'list' for a list
object. They shouldn't.

The example could have been written as:

[f for f in files if f.endswith(extension)]




More information about the Python-list mailing list