diff -r 23d9daed4b14 Doc/faq/programming.rst --- a/Doc/faq/programming.rst Tue Mar 04 23:22:15 2014 +0000 +++ b/Doc/faq/programming.rst Mon Mar 10 16:39:20 2014 +0000 @@ -391,6 +391,61 @@ the values ``42``, ``314``, and ``somevar`` are arguments. +Are variables assigned by reference or by value? +------------------------------------------------ +Variables are assigned the value of a reference to an object. However, +depending on whether an object is mutable or immutable, the behavior of +assigning a variable to another variable can appear to differ. + +Integers, strings, and tuples are examples of immutable objects. When an +immutable object is altered, a new object is created and only the variable where +the object was created is updated to reference the new object. +For example:: + + >>> x = 1 + >>> y = x + >>> x = x + 1 + >>> x + 2 + >>> y + 1 + +Because integers are immutable, ``x`` points to the new object whereas ``y`` +still points to the old object. Here is an example with tuples, which like +integers are immutable:: + + >>> a = (1,2) + >>> b = a + >>> a = a + (3,) + >>> a + (1, 2, 3) + >>> b + (1, 2) + +However, if the object being referenced is mutable, then the object can be +changed with no new object being created, as in the case of list mutation:: + + >>> a = [1, 2] + >>> b = a + >>> a.append(3) + >>> a + [1, 2, 3] + >>> b + [1, 2, 3] + +In the above example, both variables ``a`` and ``b`` reference the same object. +However, it is important to note that although lists are mutable, not all +operations mutate lists; in the case of concatenating lists, a new list is +created and therefore the variables ``x`` and ``y`` in the example below +reference different objects:: + + >>> x = [1, 2] + >>> y = x + >>> x = x + [3] + >>> x + [1, 2, 3] + >>> y + [1, 2] How do I write a function with output parameters (call by reference)? ---------------------------------------------------------------------