0

Context:

  • Python 3.9
  • I have a list thetas with 2 values. I initiate this list with some initial values. I intend to update this list in-place for every iteration.
  • I have another list theta_history where I intend to store the value of thetas for every iteration using update_thetas function.

Issue: theta_history ends up becoming a list of length = iterations, but only the final value of thetas repeated instead of the values from each iteration.

Approach (I am using .append(), but have also tried using .insert(ind, val) - with same results)

def update_thetas(thetas):
    for i in range(len(thetas)):
        thetas[i] = thetas[i] + 1
    print(f"thetas: {thetas}")
    return thetas

thetas = [0] * 2
thetas[0] = 10
thetas[1] = 5
theta_history = []
iterations = 3
for i in range(iterations):
    theta_history.append(thetas)
    thetas = update_thetas(thetas)
print(f"theta_history: {theta_history}")

This produces:

thetas: [11, 6]
thetas: [12, 7]
thetas: [13, 8]
theta_history: [[13, 8], [13, 8], [13, 8]]

What I want:

theta_history: [[11, 6], [12, 7], [13, 8]]

Thanks!

DaytaSigntist
  • 117
  • 2
  • 8

2 Answers2

1

You're just storing a reference in theta_history, so you need to make a copy of the list each time.

You can do a simple copy with the spread operator (*). If you were doing something with more complicated innards, you would need to do a deep copy (which you can search online about).

for i in range(iterations):
    theta_history.append([*thetas])
    thetas = update_thetas(thetas)
print(f"theta_history: {theta_history}")

Output:

thetas: [11, 6]
thetas: [12, 7]
thetas: [13, 8]
theta_history: [[10, 5], [11, 6], [12, 7]]
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
1

You can make a copy of the value of thetas using list or tuple function instead of appending a reference to thetas.

theta_history.append(tuple(thetas))
foo = ["a", "b", "c"] # original list
bar = foo # a reference to foo
baz = list(foo) # copy value of foo into baz
AntumDeluge
  • 490
  • 1
  • 5
  • 13