0

I want to create a list that contains the monomials up to degree n

basis = [lambda x:x**i for i in range(0,n+1)]

This however creates a list of n functions, but all the same one (of degree n) and not of degree 0,1,2,...n

I tried without list comprehension as well:

basis = []
for i in range(0,n+1):
    basis.append(lambda x:x**i)

but with the same result. Substituting the lambda function by a classic function definition also did not fix it.


I checked Python lambdas and scoping, but that did not help, since I don't want to store function values, but the function itself. For example, I want to be able to call

basis[0](34)

and this should return

1
user2314737
  • 27,088
  • 20
  • 102
  • 114
M. Becerra
  • 639
  • 6
  • 21
  • you can do this with `partial` (https://docs.python.org/3/library/functools.html#functools.partial) but you will need a *proper* function declaration – Ma0 Feb 20 '17 at 16:36

2 Answers2

0

As i said in the comments, take a look at partial

def f(x, n):
    return x**n

basis = [partial(f, n=i) for i in range(10)]
print(basis[0](34))  # 1
Ma0
  • 15,057
  • 4
  • 35
  • 65
-1

This entry sums it up perfectly

http://docs.python-guide.org/en/latest/writing/gotchas/#late-binding-closures :

... you can create a closure that binds immediately to its arguments by using a default arg like so:

def create_multipliers():
      return [lambda x, i=i : i * x for i in range(5)]

You code would become:

basis = [lambda x,i=i:x**i for i in range(0,n+1)]

This is a bit of a hacky solution, but works. I still highly recommend to read the link provided as the 3 points that are made there are usual errors when you are new to Python.

Adirio
  • 5,040
  • 1
  • 14
  • 26