[Tutor] A couple beginner questions.

Hans Nowak hnowak@cuci.nl
Tue, 25 Sep 2001 09:51:08 +0200


>===== Original Message From Eric Henry <ehenry@imt.net> =====
>Hi there everyone.  I decided work on a small project to sort of get my
>feet wet in python and programming in general.  I've got a couple of
>quick questions for you all.  First, is there a built in way to apply
>some operation to each item in a list?  For example adding 2 to [1,2,3],
>and getting [3,4,5].

As people already pointed out, you can use map:

  x = map(lambda x: x+2, [1, 2, 3])

or without the lambda:

  def f(x): return x+2
  x = map(f, [1, 2, 3])

...but you can also use a list comprehension:

  x = [x+2 for x in [1, 2, 3])

Which one is to be used is largely a matter of preference (although reduce() 
has no equivalent with list comprehensions).

HTH,

--Hans Nowak