Trying to teach an old dog new tricks

I'm stuck in a 1970s programming mindset, and I'm trying to get my mind around the '=' operator in Python. If I have two variables 'a' and 'b', the line 'a=b' does not do what I expect. See this explanation:

http://rg03.wordpress.com/2007/04/21/semantics-of-python-variable-names-from-a-c-perspective/

I read a comment somewhere from the creator of Python that Python-newbies worry too much about this. Well, yes, I'm worried. The '=' is not really an assignment operator anymore, so 'a=b' does not copy the content of one variable to another. So, how on earth do I create two different variables 'a' and 'b' and then copy the contents of 'b' into 'a'?

In Python terminology, variables and strings are immutable. On the other hand, lists and dictionaries (associative arrays) are mutable -- and the contents of those can be copied from one to another.

But, I am left mystified. Ok, I'm a total Python newbie, and I do want to be able to do one of the most basic things that I would have done in C or Bash, copy the content of one variable to another, that is, 'a=b'. So, how do I do that in Python? -- is it obvious, and I have missed a critical point?


Posted on 4 Nov 2008, 7:43


Comments:

Posted on 4 Nov 2008, 8:05 by BarryK
Python assignment
Hmmm, maybe I am worrying abou it too much. This post:

Hi Miguel:
If str and str2 are pointing to the same blocks of memory, below is the case will happen:

str=”Hello”
str2=str
str2=”World”

Then str will become “World” as well, but that is not the case.

Maybe at the moment we do str=str2, they are pointing to the same memory, but when i do str2=”World”, str2 will spawn a new memory block. I think this will be the case.


That was posted to:
http://linux.byexamples.com/archives/350/python-careful-with-equal-sign/

'str2' is not a new variable when 'str2=str', just an alias to the same value. However, later 'str2="World"' is causing creation of a new object for 'str2'. So, perhaps in practice it is not something to worry about.


Posted on 7 Nov 2008, 22:09 by fedekun
hmm
Why python? :P
I prefer C-ish programming languages, i only use python when i have no other choice, like with google appengine