[Tutor] Re: List Comprehensions again

Paul Sidorsky paulsid@shaw.ca
Thu, 24 Jan 2002 23:52:51 -0700


Erik Price wrote:

> Where should I look for more info, or is this something that can wait
> until I am more comfortable with the language?  (I am just finishing
> tutorials on syntax so you can see that I am really really green at
> this.)

As should be evident from the debate, neither list comprehensions nor
map/lambda really make your code any nicer, so it's probably not
critical to learn them any time soon.  Better to write out what you're
doing longhand and understand it than to get "confuzzled" by what are
largely time-saving features.

However the shorthands do save a lot of work, so do try to learn them at
some point.  But not 'til you think you're ready.

When you are I'd suggest starting out slowly.  For list comprehensions,
start with basic ones that just do one thing to the object variable, and
ignore if's and multiple for's.  My favourite simple LC (probably
because it would take so much C code to do) is this:

f.writelines([line.replace(str1, str2) for line in f.readlines()])

If f is an open file, then this is a poor person's file-wide search and
replace - in one line!

Next try working just with the if's, like maybe this blank-line
filterer:

f.writelines([line for line in f.readlines() if line.strip()]

Then combine them, then try multi-for's, etc.  I think the hardest part
is learning to deal with the above two cases, though, because they're
the basics.  Once you learn how LC's work then extending them isn't too
much harder to learn.

BTW, I have noticed a lot of people - especially myself - have a
tendancy to use single-letter or other meaningless variable names in
LC's.  While this isn't too terrible since it keeps the LC brief, if you
don't understand LC's it can make things more confusing.  So it might
make it clearer to spell out what the "object variable" in the LC is
for, as I did above.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/