site  contact  subhomenews

Trying to teach an old dog new tricks

November 04, 2008 — BarryK
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?

Comments

Python assignment
Username: BarryK
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: [i]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.[/i] 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.

hmm
Username: fedekun
"Why python? :P I prefer C-ish programming languages, i only use python when i have no other choice, like with google appengine


Tags: woof