On Tue, Feb 23, 2010 at 1:13 PM, Giorgio <anothernetfel...@gmail.com> wrote: > I have an update: > I can easily undertand why this example doesn't work: > def nochange(x): > x = 0 > y = 1 > nochange(y) > print y # Prints out 1 > X is a local variable, and only gets modified in the function, that doesn't > return any value. > But it's very difficult for me to understand WHY this works: > def change(some_list): > some_list[1] = 4 > x = [1,2,3] > change(x) > print x # Prints out [1,4,3] > some_list is a "local" list, isn't it? Maybe i can't have lists that are > only existing in a function?
Here is what happens, as I understand it: When you enter the function, a new name (x, in your case) is created in the local scope. That name points to the object you supplied when you called the function (an integer object, with a value of 1). the x = 0 statement creates a new object, and has the name x now pointing to this new object. The old integer object still exists, and y still points to it. This is why the global y name is not affected by the change in x Now, in the second example, the same thing basically happens. A new name is created and pointed at the object you supplied. However, the statement some_list[1] = 4 is different from the assignment, in that it doesn't create a new object; It modifies the existing one. Since the global and local names both point to the same object, the change you make is reflected in both. You can of course create a new list object, so that the original is not affected: def nochange(some_list): # create shallow copy of list. NOTE: Shallow copies may still bite you if you change the list members. some_list = some_list[:] some_list[1] = 2 >>> x = [1, 2, 3] >>> nochange(x) >>> x [1, 2, 3] HTH, Hugo _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor