[Newby question] List comprehension
Hallvard B Furuseth
h.b.furuseth at usit.uio.no
Fri Aug 6 11:08:29 EDT 2004
Eelco Hoekema wrote:
> Batista, Facundo schreef:
>
>> Now, explain me why a list comprehension is better here.
>
> Are they better? Don't know. In Dive into Python, Mark Pilgrim states
> compared to list comprehensions, for loops are a waste of time. Not
> sure what he means by that, though.
List comprehensions are faster.
> I just like them, that's all.
Well, in your example you could cheat and use the for statement as an
assignment statement:
[(root, songs)
for (root, dir, files) in os.walk(os.path.abspath('.'))
for songs in (filter(song, files),)
if songs]
However, if you like that sort of tricks, try Perl.
Or submit a proposal to extend the list comprehension syntax:
[(root, songs)
for (root, dir, files) in os.walk(os.path.abspath('.'))
with songs = filter(song, files)
if songs]
--
Hallvard
More information about the Python-list
mailing list