Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass mutable object by value

I am altering a state dictionary in a for loop and appending the new states to a list every iteration.

In Python, dictionaries are of course mutable so what gets appended to the list is a reference to the continuously mutating dictionary object. So at the end I just get a list of the same duplicated reference, pointing to the final version of the state.

state = {'temp': 21.6, 'wind': 44.0}
state_list = []
for i in range(10):
    state['temp'] += 0.5
    state['wind'] -= 0.5
    state_list.append(state)

Is there a way to tell the interpreter that I wish to 'pass by value'? I am capable of constructing a tuple or something mutable from the state the line before the append, and appending the list with say tuples. I just want to check this is the best solution.

like image 621
sphere Avatar asked Oct 28 '25 13:10

sphere


1 Answers

Its not "passing by value", as lists actually holds the references to objects. You need to create copy and append to list, i.e.:

state_list.append(state.copy())

Note, tho, that .copy creates a shallow copy of object. For containers, this means that container is new, but it will hold the same references. As your state is described by floats, and floats is immutable, this will cause no issues whatsoever.

In case if you need to copy container with mutable objects inside and have this objects copied too, you can use deepcopy

like image 71
Slam Avatar answered Oct 31 '25 03:10

Slam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!