[Tutor] list comprehension, efficiency?

Bill Allen wallenpb at gmail.com
Tue Sep 28 05:57:23 CEST 2010


I have seen list comprehensions used, but have not quite got the hang of it
yet.
So, I was writing a bit of code to do some work with file directories and
decided
to give it a try as follows:

list_c = os.listdir("c:")

#first code written in the way I usually would.
dirs = []
for x in list_c:
    if os.path.isdir(x):
        dirs.append(x)

#replaced the above code with the following list comprehension, it worked as
expected:
dirs = [x for x in list_c if os.path.isdir(x)]

I can now see that quite a bit of the code I write dealing with lists can be
done with list
comprehensions.   My question is this, is the list comprehension styled code
generally
more efficient at runtime?  If so, why?

--Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100927/11ec90c0/attachment.html>


More information about the Tutor mailing list