From: stephan at pcrm.win.tue.nl (Stephan Houben)
Date: 23 Apr 1999 15:10:50 +0200
Subject: opening more than 1 file
References: <371CB255.5FCAFBAF@solair1.inter.NL.net> <371CCAE0.7DE87F8A@aw.sgi.com> <7fpteh$cik$1@news1.xs4all.nl>
Message-ID: <m3vhenlbxh.fsf@pcrm.win.tue.nl>
Content-Length: 1924
X-UID: 127                                                  

"Gornauth" <gornauth at dds.nl> writes:

> Gary Herron wrote in message <371CCAE0.7DE87F8A at aw.sgi.com>...
> >files = map(lambda i: open("file%02d"%i, 'w'), range(N))
> 
> I'm not completely sure how that one-liner works. To be honest, I have no
> clue whatsoever.

The above fragment is equivalent to:

  def open_file(i):
      filename = "file%02d" % i
      file = open(filename, 'w')
      return file

  files = map(open_file, range(N))

And the last line could be replaced by:

  files = []
  for i in range(N):
      file = open(file(i))
      files.append(file)	

Basically, 'lambda' is handy when you need to "def"ine a function but
don't want to define a function, and map is handy when you need to do a
for-loop but you don't want to do a for-loop. This allows one to write
"simple" (as in "short") programs.  

> Could someone more python-literate please be so kind as to give a couple of
> examples on how to use 'map' and 'lamba'?

To start with map(): map() applies a given function to every element
of a given list. In most cases, the same result could have been had
with a for-loop. It is best for simple functions, especially built-ins,
because in that case it's faster than the resulting for-loop, and for
a simple function I find map often clearer.

e.g. you have a list with integers and want to convert them all to strings:

  strlist = map(str, intlist)

as opposed to:

  strlist = []
  for i in intlist:
      strlist.append(str(i))

I find the first possibility not only shorter, but also more readable.

Lambda lets you create a simple one-shot function.
It is most useful when you need to pass a function as an argument, and
the function you want to pass is very simple.

You *can* combine map and lambda to simulate very complex for-loops.
However, I think that in that case it's usually better to write out
the for-loop.


> 
> Met vriendelijke groeten,
>         Hans

Groeten,

Stephan




