python - Sympy and lambda functions -


i want generate list of basic monomial x^0 x^n (in particular, n=9) using sympy. quick solution simple list comprehension combined python's lambda function syntax:

import sympy sym x = sym.symbols('x')  monomials = [lambda x: x**n n in range(10)] 

however, when verify monomials constructed expected, find that:

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

if redefine monomials without using lambda syntax, otherwise expect:

monomials = [x**n 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 behavior?


specs:

  • python 3.5.1
  • sympy 1.0

i using anaconda 2.5.0 (64-bit) package manager.

you need use second arg default value

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

otherwise have closure , not value reference n.


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -