Missing Something Simple

Fuzzyman fuzzyman at gmail.com
Tue Jul 12 16:29:17 CEST 2005


Hello John,

John Abel wrote:
> harold fellermann wrote:
>
> >Hi,
> >
> >
> >
> >>I have a list of variables, which I am iterating over.  I need to set
> >>the value of each variable.  My code looks like:
> >>
> >>varList = [ varOne, varTwo, varThree, varFour ]
> >>
> >>for indivVar in varList:
> >>    indivVar = returnVarFromFunction()
> >>
> >>However, none of the variables in the list are being set.
> >>
> >>
> >
> >You only change the value of the local variable in the body
> >of the for loop. it has no effect on the list. you could do e.g.
> >
> >varList = [vorOne,varTwo,varThree,varFour]
> >for i in len(varList) :
> >	varList[i] = returnVarFromFunction()
> >
> >However, as in this example the former list values are not used anyway,
> >you could just write:
> >
> >varList = [ returnVarFromFunction for i varList ]
> >
> >
> >cheers,
> >
> >- harold -
> >
> >--
> >Tages Arbeit, abends Gäste,
> >saure Wochen, frohe Feste!
> >-- Johann Wolfgang v. Goethe
> >
> >
> >
> The problem I have, is the variables are referenced elsewhere.  They
> have been declared before being used in the list.  Basically, I'm after
> the Python way of using deferencing.
>

The problem you have is that you don't understand the way that Python
references objects.

All Python names (aka variables) are references. You can rebind a name
to *any* object, but you can only change *some* objects. These are
called the mutable datatypes. The ones you can't changed are called
immutable types.

This is a common Python gotcha - but it's an integral part of the way
Python works - not a wart.

Your problem (I think) is that you have something like :

myVar = 'hello'
another_name = myVar
another_name = 'goodbye'
print myVar
   'hello'

but you expected 'goodbye'.

What you have done in the first line is created a new - a string with
the contents 'hello' - and bound the name

In the second line you bind another name to the *same* object. (You
*don't* bind the second name to the first name, but to the object it
references).

In the third line you create a new object and *rebind* the second name.
You haven't chanegd the underlying object. In Python the string is
immutable. This means it's hashable and can be used as a dictionary
key.

If you want to maintain a reference to a *location* then use a mutable
datatype. Instead of a list use a dictionary, keyed by name (as one
example).

e.g. a_dict = {'name1': object1, 'name2': object2}

Even if you change the contents of the dictionaries, the names will
still point to what you expect. (And you can still iterate over a
dictionary).

Before you get much further in Python you'll need a clearer
understanding of the difference between it's objects and names.

Best Regards,

Fuzzy
http://www.voidspace.org.uk/python

> J




More information about the Python-list mailing list