Thinking Pythonically (was Re: gah! I hate the new string syntax)

Mark Pilgrim f8dy at diveintopython.org
Sat Mar 3 02:55:54 EST 2001


in article 7k31at0hbkuqgjtnsfts9nieskove1nli4 at 4ax.com, Kirby Urner at
urner at alumni.princeton.edu wrote on 3/3/01 1:41 AM:
> Pilgrim's use of list comprehensions wherever suitable doesn't
> seem a dive into an arcane or cryptic style.  The 'map' thing
> was cumbersome, because if your function had two or more
> parameters, but you wanted to hold one or more of them constant,

Heh heh, he said "Dive Into". :)

I agree completely with Kirby.  I mentioned this in passing earlier in this
thread, but it bears repeating: the map/lambda solution is awkward no matter
how you cut it.  Consider the example of getting a list of fully qualified
pathnames of the contents of a directory, something I do all the time.  You
could certainly do this with map:

>>> map(lambda f, dirname=dirname: os.path.join(dirname, f),
os.listdir(dirname))

That's awkward because of the "dirname=dirname" hack required by the lack of
nested scopes.  (Yes, yes, I know this will be solved in Python
2.1^H^H^H2.2^H^H^H2.3.)  Or you could break it up into two steps, like this:

>>> fileList = os.listdir(dirname)
>>> map(os.path.join, [dirname]*len(fileList), fileList)

That's awkward because of the list multiplication, and it has to be done in
two steps because you don't know how long the list will be ahead of time.
Or you could just use a list comprehension, like this:

>>> [os.path.join(dirname, f) for f in os.listdir(dirname)]

To me, that says "for each of the files in this directory, make a full
pathname out of it, and give me a list of all of those."  I don't know what
the map examples say, other than "I'm trying to do something simple and this
language is making it hard."  If I wanted to feel like that, I'd go back to
Powerbuilder.

-M
You're smart; why haven't you learned Python yet?
http://diveintopython.org/




More information about the Python-list mailing list