Is there a way in to make copy of a variable so that when the value changes of variable ‘a’ it copies itself to variable ‘b’?
Example
a='hello'
b=a #.copy() or a function that will make a copy
a='bye'
# Is there a way to make
# 'b' equal 'a' without
# doing 'b=a'
print a
print b
I am having a problem using the Tkinter library where I have checkbutton that has been stored in a list and I’m trying to get the variable that it holds.
But it takes around 5 lines of code to reach the variable.
You’re exploring how Python deals with references. Assignment is simply binding a reference to an object on the right hand side. So, this is somewhat trivial:
However, as soon as you do:
Now this becomes really interesting with objects which are mutable:
In this case,
achanges becausebandaare referencing the same object. When we make a change tob(which we can do since it is mutable), that same change is seen atabecause they’re the same object.So, to answer your question, you can’t do it directly, but you can do it indirectly if you used a mutable type (like a list) to store the actual data that you’re carrying around.
This is something that is very important to understand when working with Python code, and it’s not the way a lot of languages work, so it pays to really think about/research this until you truly understand it.