2

I want to generate a list of basic monomial from x^0 to x^n (in particular, n=9) using Sympy. My quick solution is a simple list comprehension combined with Python's lambda function syntax:

import sympy as sym
x = sym.symbols('x')

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

However, when I verify that monomials is constructed as expected, I find that:

print([f(x) for f in monomials])
>>> [x**9, x**9, x**9, x**9, x**9, x**9, x**9, x**9, x**9, x**9]

If I redefine monomials without using the lambda syntax, I get what I would otherwise expect:

monomials = [x**n for n in range(10)]
print(monomials)
>>> [1, x, x**2, x**3, x**4, x**5, x**6, x**7, x**8, x**9]

Why do I get this behavior?


Specs:

  • Python 3.5.1
  • Sympy 1.0

I am using the Anaconda 2.5.0 (64-bit) package manager.

user
  • 5,370
  • 8
  • 47
  • 75

1 Answers1

0

You need to use second arg with default value

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

otherwise you have a closure and get not value but reference to n.

user
  • 5,370
  • 8
  • 47
  • 75
knagaev
  • 2,897
  • 16
  • 20