Entry
List of references
Jul 5th, 2000 09:59
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 50, Jay Glascoe
"""
Packages: basic_datatypes.lists;new_datatypes
"""
"""
> I have to hold a list of references to python float values
> and then change the values in the list. But the following
> doesn't work:
>
> >>> a=1.0
> >>> b=2.0
> >>> c=3.0
> >>> l=[a,b,c]
> >>> l[0]=1.1
> >>> print l
> [1.1, 2.0, 3.0]
> >>> print a
> 1.0
>
> I would like to have a=1.1
[I'm going to go ahead and switch "l" to "el", -ed.]
hi, I think that when you do "el = [a, b, c]", then your
list, el, is storing references to the values that a, b, c
are themselves referring to (i.e., it's storing references
to *values*, not references to *references to values*).
how about this:
"""
class MyRef:
def __init__(self, val=None):
self.val = val
def __repr__(self):
return "->%s" % self.val
a = MyRef(1.0)
b = MyRef(2.0)
c = MyRef(3.0)
el = [a, b, c]
print el
# [->1.0, ->2.0, ->3.0]
el[0].val = 1.1
print el
#[->1.1, ->2.0, ->3.0]
print a
# ->1.1