On 2008-10-01, Ross <[EMAIL PROTECTED]> wrote: > Forgive my newbieness - I want to refer to some variables and > indirectly alter them. Not sure if this is as easy in Python > as it is in C.
Python doesn't have variables. It has names bound to objects. When you do an assignment, that binds (or rebinds) a name to an object. There is no such thing as a C-like "variable" (a named region of memory with a fixed location into which you can write different values). Some objects (e.g. lists, dictionaries) are mutable (you can change their value or contents), some objects (e.g. strings, integers, floats) are not mutable. > Say I have three vars: oats, corn, barley > > I add them to a list: myList[{oats}, {peas}, {barley}] > > Then I want to past that list around and alter one of those > values. That is I want to increment the value of corn: > > myList[1] = myList[1] + 1 > > Is there some means to do that?. Here's my little session > trying to figure this out: > > >>> oats = 1 > >>> peas = 6 Those two lines created two integer objects with values 1 and 6 and bound the names "oats" and "peas" to those two objects. > >>> myList=[] > >>> myList > [] > >>> myList.append(oats) That line finds the object to which the name "oats" is currently bound and appends that object to the list. > >>> myList > [1] > >>> myList.append(peas) Likewise for the object to which the name "peas" is currently bound. > >>> myList > [1, 6] > >>> myList[1]= myList[1]+1 That line creates a new integer object (whose value happens to be 7) and replaces the object at position 1 in the list with the new object. > >>> myList > [1, 7] > >>> peas > 6 > >>> > > So I don't seem to change the value of peas as I wished. Correct. The name "peas" is still bound to the same object it was before > I'm passing the values of the vars into the list, not the vars > themselves, as I would like. There are no "vars" as the word is used in the context of C programming. Just names and objects. Here's an article explaining it: http://rg03.wordpress.com/2007/04/21/semantics-of-python-variable-names-from-a-c-perspective/ A couple other good references: http://starship.python.net/crew/mwh/hacks/objectthink.html http://effbot.org/zone/python-objects.htm -- Grant Edwards grante Yow! What GOOD is a at CARDBOARD suitcase ANYWAY? visi.com -- http://mail.python.org/mailman/listinfo/python-list