cmlcrz
cmlcrz

Reputation: 21

Storing every value of a changing variable

I am writing a piece of code that takes an input that varies according to discrete time steps. For each time step, I get a new value for the input. How can I store each value as a list?

Here's an example:

"""when t = 0, d = a
   when t = 1, d = b
   when t = 2, d = c"""

n = []
n.append(d)      #d is the changing variable
for i in range(t):
    n.append(d)

What I expect to get is: for t = 0, n = [a]; for t = 1, n = [a,b]; and for t = 2, n = [a,b,c]

What I actually get is: for t = 0, n = [a], for t = 1, n = [b,b]; and for t = 2, n = [c,c,c]

Upvotes: 0

Views: 366

Answers (5)

Ivan Vega
Ivan Vega

Reputation: 21

Which type is the variable 'd'? If it is, for instance a list, the code you are showing pushes onto tbe list 'n' a reference to the variable 'd' rather than a copy of it. Thus, for each iteration of the loop you add a new reference of 'd' (like a pointer in C) to 'n', and when 'd' is updated all the entries in 'n' have, of course, the same value To fix it you can modify the code so as to append a copy of 'd', either:

  • n.append(d[:])
  • n.append(list(d))
  • n.append(tuple(d))

Upvotes: 2

Kavin Eswaramoorthy
Kavin Eswaramoorthy

Reputation: 1625

If you just wrap the variable inside an object you can watch what is being set to the variable by overriding __setattr__ method. A simple example.

class DummyClass(object):
    def __init__(self, x):
        self.history_of_x=[]
        self.x = x
        self._locked = True
    def __setattr__(self, name, value):
        self.__dict__[name] = value
        if name == "x":
            self.history_of_x.append(value)

d = DummyClass(4)
d.x=0
d.x=2
d.x=3
d.x=45
print d.history_of_x

Output :-

[4, 0, 2, 3, 45]

Upvotes: 0

cggarvey
cggarvey

Reputation: 585

See comment below, but based on the additional info you've provided, replace this:

n.append(d)

with this:

n.append(d[:])

Upvotes: 2

Patrick
Patrick

Reputation: 596

It is difficult to say without seeing the code. But if d is not an int, this could happen. If d is a list for instance, it is passed by reference

n = []
d = [1]
n.append(d)

d[0] = 2
n.append(d)
print(n)
>>>> [[2], [2]]

So if each new d is just modified, your probleme arise. You can solve it by copying d :

from copy import copy
n = []
d = [1]
n.append(copy(d))

d[0] = 2
n.append(copy(d))
print(n)
>>>> [[1], [2]]

Upvotes: 0

Naman Sogani
Naman Sogani

Reputation: 959

You can simply do this

n = []
for i in range(t + 1):
    n.append(chr(i+ord('a'))

And if you do not want to store the characters in the list rather some specific values which are related with d, then you have to change d in the for loop

n = []
d = 1
for i in range(t + 1):
    n.append(d)
    d += 2

Upvotes: 1

Related Questions