global lists

A

andrea crotti

Hi everbybody again,
I have a little "problem", I don't understand the reason of this:

a = [10,1,2,3]
def foo():
global a
for el in a:
el = el*2

This doesn't make any difference, if I do
def foo():
global a
a[0] = 4

But

def foo():
global a
for n in range(len(a)):
a[n] = a[n]*2

Doesn't work either...
So I think that's pretty weird, why this happen?
I have to create a new list and assign it back to get it working??
Thaks
 
B

Bernd Nawothnig

I have a little "problem", I don't understand the reason of this:
a = [10,1,2,3]
def foo():
global a
for el in a:
el = el*2

Simple data types (as integer) are _not_ implemented as references as
you obviously expected. Instead el is copied by value from each a[n].
Thus you only changed temporary copies.

The whole list instead _is_ a reference. If you write

b = a
b[0] = 57

a[0] will be effected too.

This doesn't make any difference, if I do
def foo():
global a
a[0] = 4

That should alter a[0].
But

def foo():
global a
for n in range(len(a)):
a[n] = a[n]*2

Doesn't work either...

It does. Test it again.



Bernd
 

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

Forum statistics

Threads
474,238
Messages
2,571,193
Members
47,830
Latest member
ZacharySap

Latest Threads

Top