Jump to content

I tried this code which doesn 't work, the two lists point to the same object Python has names,...


G+_Tadeusz Cantwell
 Share

Recommended Posts

I tried this code which doesn't work, the two lists point to the same object. Python has names, not variables.

 

from random import shuffle

 

main_list = ['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']

rand_list = main_list

shuffle(rand_list)

print main_list

print rand_list

 

http://stackoverflow.com/questions/986006/python-how-do-i-pass-a-variable-by-reference

 

http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables

 

Repeat after me!

for(i = 0; i < 10; i++) {

    System.out.println("Python is not Java");

}

http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables

Link to comment
Share on other sites

Actually, two variables with the same primitive value ARE pointing to the same object in Python. Python creates space for these primitive objects as needed, and treats them as immutable objects, but objects nonetheless. If you type

 

a = 5

b = 5

 

in Python, there is only one object--a newly allocated "box" if you like--with the immutable value 5, and both names a and b point to it. If you then do

 

a += 1

 

since primitive objects are immutable, Python must allocate a new box for the primitive object 6, and make a point to that. Both of these primitive objects will stay in memory until no more variables point to them.

Link to comment
Share on other sites

 Share

×
×
  • Create New...