G+_Tadeusz Cantwell Posted May 9, 2014 Share Posted May 9, 2014 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 More sharing options...
G+_Lee Crocker Posted May 9, 2014 Share Posted May 9, 2014 The built-in function list() creates a new list from its arguments, so what you meant was rand_list = list(main_list) . . . (Or the common, but harder to read, rand_list = main_list[:] ) Link to comment Share on other sites More sharing options...
G+_Jayunderwood Kent Posted May 9, 2014 Share Posted May 9, 2014 your question is not very clear what is it your asking? Link to comment Share on other sites More sharing options...
G+_Tadeusz Cantwell Posted May 9, 2014 Author Share Posted May 9, 2014 Was more making an observation instead, maybe I should have used the code example instead of question. Basically putting stuff out their I find interesting. Thanks Lee Crocker for giving an easy way to get around naming. Link to comment Share on other sites More sharing options...
G+_Lee Crocker Posted May 10, 2014 Share Posted May 10, 2014 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 More sharing options...
Recommended Posts