faqts : Computers : Programming : Languages : Python : Snippets : Lists

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 4 people (50%) answered Yes
Recently 1 of 3 people (33%) answered Yes

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