By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,906 Members | 1,771 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,906 IT Pros & Developers. It's quick & easy.

just curious

P: n/a
I'm new to Python, and I've noticed the following:
def f(a,b): a+=b def g(a,b): a=a+b p=[1,2,3]
q=[4,5,6]
r=[7,8,9]
s=[10,11,12]
f(p,q)
p [1, 2, 3, 4, 5, 6] g(r,s)
r

[7, 8, 9]

Any deep reason for this, or "just because"? TIA.

Peace,
EJ
Jul 18 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Elaine Jackson wrote:
Any deep reason for this, or "just because"? TIA.


It's because the augmented assignment operators, like +=, are supposed
to efficiently mutate objects when they have the opportunity (at least
for the builtin classes). So a = a + b always creates a new object, but
a += b might just mutate a preexisting object if that option is
available.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/ \ The great floodgates of the wonder-world swung open.
\__/ Herman Melville
Jul 18 '05 #2

P: n/a

"Elaine Jackson" <el***************@home.com> schrieb im Newsbeitrag
news:rn***********************@news2.calgary.shaw. ca...
I'm new to Python, and I've noticed the following:

(1) Python has a quite strict "call by value" similar to C. This means - as
in C) you can use formal parameters as if they were local variables. (And
there are some useful tricks with that..)
So A = A + B will have no outside impact.

(2) A += B for lists is a shortcut for
A.extend(B)
which means that it changes something A is bound to (or "points to" as you
would say in C). This is somewhat awkward because it sometimes works counter
intuitive as in your case. Just keep in mind: A+=B is *not* A=A+B but
behaves as if in most cases.... ;-)

Kindly
Michael P


def f(a,b): a+=b def g(a,b): a=a+b p=[1,2,3]
q=[4,5,6]
r=[7,8,9]
s=[10,11,12]
f(p,q)
p [1, 2, 3, 4, 5, 6] g(r,s)
r

[7, 8, 9]

Any deep reason for this, or "just because"? TIA.

Peace,
EJ

Jul 18 '05 #3

P: n/a
Hi !

In
def g(a,b):
a=a+b

a new object "a" is create ; but it's a local object, who are not the "a"
global.
In python, variables are "pointer to object".

If you try :
def g(a,b):
global a
a=a+b
You obtain : "name 'a' is global and local"

@-salutations
--
Michel Claveau
Jul 18 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.