6
a = [] a.append(lambda x:x**0) 
a.append(lambda x:x**1)

a[0](2), a[1](2), a[2](2)... spits out 1, 2, 4, ...

b=[]
for i in range(4)
    b.append(lambda x:x**i)

b[0](2), b[1](2), b[2](2)... spits out 8, 8, 8, ...

In the for loop, the i is being passed to lambda as a variable, so when I call it, the last value of i is used instead of the code running as it does with a[]. (ie b[0] should use x^1, b[1] should use x^2, ...)

How can I tell lambda to pick up the value of i instead of the variable i itself.

2
  • 1
    -1: Lambdas :-(. Just def a function and it's much more clear what's going on. Commented Apr 17, 2009 at 14:52
  • I'd recommend when asking questions to explain your problem/situation before quoting (pseudo)code. Commented Apr 17, 2009 at 18:30

3 Answers 3

8

Ugly, but one way:

for i in range(4)
    b.append(lambda x, copy=i: x**copy)

You might prefer

def raiser(power):
    return lambda x: x**power

for i in range(4)
    b.append(raiser(i))

(All code untested.)

Sign up to request clarification or add additional context in comments.

1 Comment

tested the first one: works just fine..
4

Define a factory

def power_function_factory(value):
    def new_power_function(base):
        return base ** value
    return new_power_function

b = []
for i in range(4):
    b.append(power_function_factory(i))

or

b = [power_function_factory(i) for i in range(4)]

Comments

2
b=[]
f=(lambda p:(lambda x:x**p))
for i in range(4):
   b.append(f(i))
for g in b:
   print g(2)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.