Catherine Moroney <catherine.m.moro...@jpl.nasa.gov> writes: > Is there a way to create a C-style pointer in (pure) Python so the > following code will reflect the changes to the variable "a" in the > dictionary "x"?
No, Python doesn't do pointers. Rather, objects have references and that's how the program accesses the objects. > For example: > > >>> a = 1.0 > >>> b = 2.0 > >>> x = {"a":a, "b":b} > >>> x > {'a': 1.0, 'b': 2.0} > >>> a = 100.0 > >>> x > {'a': 1.0, 'b': 2.0} ## at this point, I would like the value > ## associated with the "a" key to be 100.0 > ## rather than 1.0 You might like that, but it's just not how Python works. Python doesn't have C-style pointers. Python also doesn't have variables (even though the documentation uses that term; IMO it's a mistake, and leads to confusion similar to this). What Python has are references to objects. One kind of reference is a name; another kind of reference is a value in a dictionary. The assignment operator ‘=’ is the binding operator. It binds the reference on the left side to the object on the right side. > If I make "a" and "b" numpy arrays, then changes that I make to the > values of a and b show up in the dictionary x. Yes, because the objects are mutable; you can change them and existing references are still referring to the same object. They don't “show up in the dictionary”; the dictionary item is just referring to the same object it did before you made the change. > My understanding is that when I redefine the value of "a" Please think of it, instead, as re-binding the name ‘a’ to a new value. > that Python is creating a brand-new float with the value of 100.0, Yes (or at least that's the abstraction being presented to you; it may not be implemented exactly that way, but it's sufficient that we Python programmers treat it that way). > whereas when I use numpy arrays I am merely assigning a new value to > the same object. No, you're modifying the object. A numpy array itself contains references. By altering one of the elements in an array, you are re-binding one of its references to a different number. > Is there some way to rewrite the code above so the change of "a" from > 1.0 to 100.0 is reflected in the dictionary. I would like to use > simple datatypes such as floats, rather than numpy arrays or classes. Please follow the Python tutorial <URL:http://docs.python.org/tutorial/> from beginning to end. Not just read, but do it: work through the exercises to understand what each one is teaching you. That will give you a firm grounding in Python's data model, including mutable and immutable types, references and binding. Do bear in mind what I said above, though, about “variable” being a misleading term, and ignore its implications from the C language. -- \ “Good judgement comes from experience. Experience comes from | `\ bad judgement.” —Frederick P. Brooks | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list