Page 1 of 1

[SOLVED] The value of persistent list changes if its value is assigned to a regular variable and changed it

Posted: Sat Nov 25, 2023 4:02 am
by NoFanru
I have a list as a persistent variable and I need to assign its value to a regular variable and change the value of the regular variable using Python methods for lists. However, changing the value of a regular variable also changes the value of persistent. Here's a simple example of what's happening:

Code: Select all

    $ persistent.kk = [0, 1, 2]

    "[persistent.kk]" # [0, 1, 2]

    $ n = persistent.kk
    $ n.append(0)

    "[persistent.kk]" # [0, 1, 2, 0] ????
So, is it possible to change a regular variable without changing the persistent variable?
I would be grateful for any help

Re: The value of persistent list changes if its value is assigned to a regular variable and changed it using methods of

Posted: Sat Nov 25, 2023 4:59 am
by Ocelot
Yes, you just need to make sure that regular variable points to a copy and not the same list your persistent variable points to.
Choose your approach:

Code: Select all

$ n = persistent.kk.copy()
$ n = persistent.kk[:]
$ n = list(persistent.kk)

Re: The value of persistent list changes if its value is assigned to a regular variable and changed it using methods of

Posted: Sat Nov 25, 2023 5:18 am
by m_from_space
NoFanru wrote: Sat Nov 25, 2023 4:02 am So, is it possible to change a regular variable without changing the persistent variable?
I would be grateful for any help
This has nothing to do with persistent or regular variables. It's just a Python thing. If you want to create a copy of a list (or dictionary etc.) you have to do it in a way @Ocelot describes. Otherwise in Python you would just create a reference. It's how Python works, not Renpy.

Re: The value of persistent list changes if its value is assigned to a regular variable and changed it using methods of

Posted: Sat Nov 25, 2023 6:36 am
by NoFanru
Ocelot wrote: Sat Nov 25, 2023 4:59 am Yes, you just need to make sure that regular variable points to a copy and not the same list your persistent variable points to.
Choose your approach:

Code: Select all

$ n = persistent.kk.copy()
$ n = persistent.kk[:]
$ n = list(persistent.kk)
Ohh, thank you very much for your help, and I'm sorry that my question was so stupid, haha :<