indirectly addressing vars in Python

Chris Rebert clp at rebertia.com
Wed Oct 1 11:15:57 EDT 2008


On Wed, Oct 1, 2008 at 7:53 AM, Ross <nobody at nospam.noway> wrote:
> Forgive my newbieness - I want to refer to some variables and indirectly
>  alter them.  Not sure if this is as easy in Python as it is in C.
>
> Say I have three vars: oats, corn, barley
>
> I add them to a list: myList[{oats}, {peas}, {barley}]

You mean:
myList = [oats, peas, barley]

And you're not adding *variables* to a list, you're adding *values* to
the list. The list elements (and the Python runtime) have *no idea*
what variables they are/were bound to.

>
> Then I want to past that list around and alter one of those values. That is
> I want to increment the value of corn:
>
> myList[1] = myList[1] + 1

This won't do what you're expecting. Integers in Python are immutable,
so instead of changing the value of 'corn', you're calculating a new
int object and overwriting the first element of the list with it.

>
> Is there some means to do that?.   Here's my little session trying to figure
> this out:
>
>>>> oats = 1
>>>> peas = 6
>>>> myList=[]
>>>> myList
> []
>>>> myList.append(oats)
>>>> myList
> [1]
>>>> myList.append(peas)
>>>> myList
> [1, 6]
>>>> myList[1]= myList[1]+1
>>>> myList
> [1, 7]
>>>> peas
> 6
>>>>
>
> So I don't seem to change the value of peas as I wished.  I'm passing the
> values of the vars into the list, not the vars themselves, as I would like.
>
> Your guidance appreciated...

Python uses *call-by-object*, not call-by-value or call-by-reference
semantics, so unlike C/C++ but like Java you can't make a "reference"
to a variable and use that to non-locally rebind the variable to a new
value. To do what you want, you need to create a mutable value that
can be updated. You could code a "MutableInt" class wrapping 'int', or
you could use a dictionary to hold the values and then always refer to
the values using the dictionary. There are a few other ways to do it.

Hope that elucidates it for you somewhat. Then again I am a little
short on sleep :)

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

>
> Ross.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list