473,763 Members | 1,373 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

indirectly addressing vars in Python

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}]

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

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...

Ross.
Oct 1 '08 #1
5 3170
Ross wrote:
>>myList[1]= myList[1]+1
The problem is this makes myList[1] point to a new integer, and not the one
that peas points to.

Python 2.5.1 (r251:54863, Jul 10 2008, 17:25:56)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2
Type "help", "copyright" , "credits" or "license" for more information.
>>oats=[1]
peas=[6]
mylist = [oats, peas]
mylist[1][0] = mylist[1][0]+1
mylist
[[1], [7]]
>>peas
[7]

This is because integers are immutable, but lists are mutable.

--
Jeremy Sanders
http://www.jeremysanders.net/
Oct 1 '08 #2
On 2008-10-01, Ross <no****@nospam. nowaywrote:
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.
Python doesn't have variables. It has names bound to objects.
When you do an assignment, that binds (or rebinds) a name to an
object. There is no such thing as a C-like "variable" (a named
region of memory with a fixed location into which you can write
different values).

Some objects (e.g. lists, dictionaries) are mutable (you can
change their value or contents), some objects (e.g. strings,
integers, floats) are not mutable.
Say I have three vars: oats, corn, barley

I add them to a list: myList[{oats}, {peas}, {barley}]

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

Is there some means to do that?. Here's my little session
trying to figure this out:
>oats = 1
peas = 6
Those two lines created two integer objects with values 1 and 6
and bound the names "oats" and "peas" to those two objects.
>myList=[]
myList
[]
>myList.append( oats)
That line finds the object to which the name "oats" is
currently bound and appends that object to the list.
>myList
[1]
>myList.append( peas)
Likewise for the object to which the name "peas" is currently
bound.
>myList
[1, 6]
>myList[1]= myList[1]+1
That line creates a new integer object (whose value happens to
be 7) and replaces the object at position 1 in the list with
the new object.
>myList
[1, 7]
>peas
6
>>

So I don't seem to change the value of peas as I wished.
Correct. The name "peas" is still bound to the same object it
was before
I'm passing the values of the vars into the list, not the vars
themselves, as I would like.
There are no "vars" as the word is used in the context of C
programming. Just names and objects.

Here's an article explaining it:

http://rg03.wordpress.com/2007/04/21...c-perspective/

A couple other good references:

http://starship.python.net/crew/mwh/...jectthink.html
http://effbot.org/zone/python-objects.htm

--
Grant Edwards grante Yow! What GOOD is a
at CARDBOARD suitcase ANYWAY?
visi.com
Oct 1 '08 #3
On Wed, Oct 1, 2008 at 7:53 AM, Ross <no****@nospam. nowaywrote:
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.appen d(oats)
myList
[1]
>>>myList.appen d(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
Oct 1 '08 #4
Chris Rebert a écrit :
On Wed, Oct 1, 2008 at 7:53 AM, Ross <no****@nospam. nowaywrote:
>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*
s/values/references to objects/, actually

(snip)
Oct 1 '08 #5
On Wed, 01 Oct 2008 10:53:08 -0400, Ross 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}]

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

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...

Ross.
Short answer: Python is not C.

Long answer: In python, integers are immutable (they do not change), i.e.
if you do:
a = 1
b = 2
c = a + b

a + b creates a new integer object that has the value 3 and assign it to c

Other examples of immutable values are: number types, string, tuple, etc.

In python, "variable" is usually called "name". The concept of variable
and name is slightly different.

In C, a variable contains an object. In python, a name contains a pointer
to an object. (the term "pointer" is used a bit loosely here)

In python, a "list" is a list of pointers to objects.

i.e.:

|--"Hello World"
myList |--1
|--6

when you do, for example, myList[2] + 1
what you're doing is:
1. fetch the value of myList[2] (i.e. 6)
2. do an arithmetic addition of 6 + 1
3. create a new integer object with value 7
4. bind myList[2] to that new integer object (_new integer object_ since
integer is immutable, you cannot change its value[1])

in short, pea is left intact since pea points to integer object 6.

beware though, that things are different if myList[2] is a mutable value
instead and the operation is an in-place operation, e.g. list.sort
>>a = [1, 2]
b = [3, 2]
myList.append (a)
myList.append (b)
myList[1].sort()
myList
[[1, 2], [2, 3]]
>>b
[2, 3]

in this case a, b is mutable object, so:
myList.append(x ) binds myList to the list object pointed by x
myList[1].sort() is an in-place sort to the list object [3, 2] (i.e. it
mutates the list [3, 2] instead of creating a new list[1]).

in this case:

myList |--[1, 2]
|--[3, 2]

myList[1].sort(), being an in-place sort, modifies the list object [3, 2]
in-place. Since b points to the same list object, b's list is changed too.

To summarize, you don't usually use that line of thinking in python. If
you really insists, though is not pythonic (and is really absurd anyway),
you may use this:
>>a = [1]
b = [2]
myList.append (a)
myList.append (b)
myList[1][0] = myList[1][0] + 1
myList
[[1], [2]]
>>b
[3]

[1] Well, not always though, in CPython (the standard python reference
implementation) , small immutable values are cached as speed optimization.
This is a safe operation, except for identity testing. But that doesn't
matter much, since identity testing of immutable is moot.
[2] If you want a sorting operation that returns a new list, use sorted
(list)

Oct 1 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3600
by: Claire | last post by:
hi, i use vars() or dir() to get variables. I use them in a def block, so i get variables of that block. How can i get variables from the namespace __main__ ? I use python in interactive mode and want to have a function to get a dictionnary for python types (int, ...) and another for my types (my classes). this function will be in my pythonstartup file. If i use python in interactive mode, is there a main module defined ? i don't know...
13
1643
by: David Rysdam | last post by:
Getting no answer yesterday, I've done some investigation and I obviously don't understand how python namespaces work. Here's a test program: #!/usr/bin/python b = 2 def sumWithGlobal(a): return a + b
0
1252
by: Christopher J. Bottaro | last post by:
>From the python programming FAQ, I learned you can do this: Globals.py: gv = 1 A.py: import Globals class A: def __init__(self): print Globals.gv
3
2114
by: ken.boss | last post by:
I am a python newbie, and am grappling with a fundamental concept. I want to modify a bunch of variables in place. Consider the following: >>> a = 'one' >>> b = 'two' >>> c = 'three' >>> list = >>> for i in range(len(list)): .... list = list.upper()
6
2026
by: flamesrock | last post by:
ok, so to my knowledge, object oriented means splitting something into the simplest number of parts and going from there. But the question is- when is it enough? For example I have the following code: #def put_file(file_id, delete=False): # """ Function to put the file on the FTP Server # """ # print " FTP for this file started"
3
2056
by: Doru-Catalin Togea | last post by:
Hi! I am writing some tests and I need to place calls through the modem. Is there an API for addressing the COM ports on my machine, so that I can issue AT-commands to the modem? If this can not be done from Python, I am sure it can be done from C/C++/Java. Any tutorials/examples that you know of? Maybe calling C from Python?
3
1284
by: Jorgen Bodde | last post by:
Hi all, I wanted to solve a small problem, and I have a function that is typically meant only as a function belonging inside another function. function like; def A(): some_var = 1 def B(): some_var += 1
1
1291
by: Konstantinos Pachopoulos | last post by:
Hi, i had posted earlier for not being able to declare global vars. No i followed the suggestions and created a class, but still the vars do not seem to have a global scope. I have tried pretty much everything. Any advice appreciated... Here: ======================================================== #!/usr/bin/env jython #imports
0
160
by: Lie Ryan | last post by:
On Fri, 10 Oct 2008 00:30:18 +0200, Hendrik van Rooyen wrote: You'll find that in most cases, using integer or Boolean is enough. There are some edge cases, which requires bit addressing for speed or memory optimizations, in python, the usual response to that kind of optimization requirement is to move that part of the code to C. If, for the more usual case, you require the bit addressing because the data structure is more convenient...
0
9563
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9386
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10145
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9998
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8822
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7366
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5270
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5406
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3523
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.