473,408 Members | 2,888 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

Namespace issues...

i am very confused...why does the following script modify the global list "l":

l=[]

def x():
l.append("xyz")

x()
print l

but the same script applied to a single variable doesnt..:

l="moe"

def x():
l+="howdy"

x()
print l
Jul 18 '05 #1
3 1240

"cghost" <ph*******@aol.com> schrieb im Newsbeitrag
news:d1**************************@posting.google.c om...
| i am very confused...why does the following script modify the global list
"l":
|
| l=[]
|
| def x():
| l.append("xyz")
|
| x()
| print l
|
| but the same script applied to a single variable doesnt..:
|
| l="moe"
|
| def x():
| l+="howdy"

Python decides that a variable is local if it's ever *assigned a value in a
function*.
In this example you assign a value to l. In the first example, you do not
(you change list l
"in place"), so here this optimization does not take place.

You have to be explicit about l being a global if you assign a value to it
using the "global" statement as in:
def x():
global l
l+="howdy"

HTH,

Vincent Wehren

|
| x()
| print l
Jul 18 '05 #2
cghost wrote:
i am very confused...why does the following script modify the global list
"l":

l=[]

def x():
l.append("xyz")

x()
print l

but the same script applied to a single variable doesnt..:

l="moe"

def x():
l+="howdy"

x()
print l


It's even worse:
def add(a, b): .... a += b
....

Now consider
lst = []
add(lst, ["alpha"])
lst ['alpha'] add(lst, ["beta", "gamma"])
lst ['alpha', 'beta', 'gamma']

where add(a, b) appends b to a versus
tpl = ()
add( tpl, ("alpha",))
tpl ()

where no apparent change takes place. The difference is that list is a
mutable type i. e. its instances can be changed anytime, whereas tuples are
immutable, i. e. they cannot be changed once they are created. For lists a
+= b is implemented to append the items in b to a. The binding of a is not
changed in the process. For immutable types this is not an option - they
cannot be altered. Therefore, for tuples a += b is implemented as a = a +
b, i. e. a new tuple containing the elements of both a and b is created and
the variable a is bound to the new tuple. In the example the binding takes
place inside a function, so you never see the new tuple unless you return
it or declare the variable as global as Vincent already pointed out.
Strings are immutable too, so
s = "abc"
add(s, "def")
s

'abc'

as expected (hopefully).

Peter
Jul 18 '05 #3
In article <d1**************************@posting.google.com >,
cghost <ph*******@aol.com> wrote:

i am very confused...why does the following script modify the global list "l":

l=[]
def x():
l.append("xyz")
x()
print l

but the same script applied to a single variable doesnt..:

l="moe"
def x():
l+="howdy"
x()
print l


http://starship.python.net/crew/mwh/...jectthink.html
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

"Argue for your limitations, and sure enough they're yours." --Richard Bach
Jul 18 '05 #4

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

Similar topics

25
by: kj | last post by:
Consider the following XML document: <?xml version='1.0' encoding='UTF-8'?> <bar:foo xmlns:bar='someuri'> <baz/> </bar:foo> What namespace does baz belong to? What is this namespace bound...
7
by: Kevin Newman | last post by:
I've been toying with a namespace manager, and wanted to get some input. So what do you think? if (typeof com == 'undefined') var com = {}; if (!com.unFocus) com.unFocus = {}; ...
9
by: MDoyle | last post by:
Here is the easiest question you’ll get all day from a complete newbie. I installed Visual Studio on my laptop last night and have been tryin to write my very first C# programs this morning. I’m...
7
by: thechaosengine | last post by:
Hi all, Can anyone tell me if it is advisable (or even possible) to define a namespace across 2 or more assemblies? For example, consider the namespace SampleApplication.Data.Providers ...
4
by: Kevin Newman | last post by:
The primary problem I've had with php is the lack of namespaces, which makes OOP very difficult to organize, since you end up with large number of classes cluttering up the same namespace - which...
0
by: kaypohsingaporean | last post by:
Hi all, I am porting VC++6 code to VC++8/2005. Here's the original code: (I have replaced the greater than sign with &gt; because this forum's parser doesn't like it) template < class CharT,...
14
by: Jon Rea | last post by:
I am currently cleaning up an application which was origainlly hashed together with speed of coding in mind and therefore contains quite a few "hacky" shortcuts. As part of this "revamping"...
30
by: Pep | last post by:
Is it best to include the code "using namespace std;" in the source or should each keyword in the std namespace be qualified by the namespace tag, such as std::cout << "using std namespace" <<...
1
by: =?Utf-8?B?QWxleGFuZGVyIFd5a2Vs?= | last post by:
Thank you Wen Yuan, This did answer my question, but it took a lot of work to implement. My original code did not use any namespace so I had to modify and test some 3000 lines of code to make...
11
by: =?Utf-8?B?SmVycnkgQw==?= | last post by:
I have a machine Windows Server 2003 using IIS 6.0 and I am getting the error BC30560 prjob_ascx is ambiguous in the namespace ASP I found a fix. Deleting all the files in the...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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,...
0
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...

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.