ref to a list index

Erik Lechak elechak at bigfoot.com
Sat Mar 15 01:40:34 EST 2003


Hello all,

I know lists are mutable and ints are not.  Is there a way to
reference an index of a list.

This is what happens, and I understand why:
x = [1,2,3,4,5]
element = x[2]
element = 6
print x
>>> [1,2,3,4,5]

Is it possible to do the following (I will use a litter "pseudo perl
syntax magic" to highlight my question)?

x = [1,2,3,4,5]
element = \x[2] # I want element to be a ref to the 2nd index of
element = 6     # array x, not a ref to the int at that index
print x
>>> [1,2,6,4,5]


The following is some of the code that I want to get to work.  Even
though Dataset.err is a list, I can't seem to make use of its mutable
properties when I iterate through the set.

d=Dataset()
d.addSet([1,2] , [3,1])

for inp,out,err in d:
    err = 0            # this just makes err local
    o =  c.run(inp)
    for q in range(len(out)):
        err = err + (o[-q] - out[-q]) **2 

for inp,out,err in d:
    print err          # this just give me "None"


class Dataset:

    def __init__(self):
        self.index =0
        self.inp    =[] # array of arrays
        self.out   =[]  # array of arrays
        self.err    =[] # array of floats

    def addSet(self, inp, outp):
        self.inp.append(inp)
        self.out.append(outp)
        self.err.append(None)
 
    def __iter__(self,):
        return self

    def __getitem__(self,key):
        try:
              # this is where I could use a ref to a list index
            return [self.inp[key] , self.out[key] , self.err[key]]
        except:
            self.index =0
            raise StopIteration 
            
    def next(self):
        d =self.__getitem__(self.index)
        self.index +=1
        return d

Thanks,
Erik Lechak




More information about the Python-list mailing list