I'm not sure what to call this issue exactly, but I believe it's best if I just show a simple example of what I'm trying to do.
import matplotlib.pyplot as plt
import numpy as np
func_list = []
for i in range(1, 4):
func_list.append(lambda x: x*i) # This is just the function of a line with some slope "i"
d = np.linspace(0, 5)
for func in func_list:
plt.plot(d, func(d))
plt.grid()
plt.show()
I want this snippet to plot three different lines with different slops. Right now, it is plotting three lines with the same slope, and I know why. The value of i
(which is 3; the last iteration in the first for loop) is the same each time I call func
.
When I am appending the function to the list func_list
, how can I force it to use the value of i
at the time I am appending it to the list? I believe there is a solution using the memory address of i
instead, but even if I changed the function creation line to this: func_list.append(lambda x: x*ctypes.cast(id(i), ctyptes.py_object).value)
, it wouldn't change a thing because it would still be using the same id.