just curious

E

Erik Max Francis

Elaine said:
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.
 
M

Michael Peuser

Elaine Jackson said:
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
 
N

News M Claveau /Hamster-P

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top