looping to define a sequence of functions?

Rainer Deyke rainerd at eldwood.com
Tue Jan 6 20:47:26 CET 2004


r.e.s. wrote:
> Suppose we want to define ten functions such that the
> nth function of x simply returns x**n. Is there a way
> to avoid explicitly writing ten function def's? (They
> have to be ten distinct functions, not just a single
> one like def f(n,x): return x**n.)

functions = [lambda x, n=n: x**n for n in range(10)]

-or-

class X(object):
  def __init__(self, n):
    self.n = n
  def __call__(self, x):
    return x ** self.n
functions = [X(n) for n in range(10)]

-or-

functions = []
for n in range(10):
  def f(x, n=n):
    return x**n
  functions.append(f)

-or-

def create_function(n):
  def f(x):
    return x**n
  return f
functions = [create_function(n) for n in range(10)]


-- 
Rainer Deyke - rainerd at eldwood.com - http://eldwood.com





More information about the Python-list mailing list