[Tutor] Tuple (Section 9.3)

Kaushal Shriyan kaushalshriyan at gmail.com
Tue Apr 11 12:26:16 CEST 2006


Hi All

I am reading this http://www.ibiblio.org/obp/thinkCSpy/chap09.htm and
did not understood the Section 9.3 at all, Please explain me with an
example so the idea become clear and understood

####################################################################

9.3 Tuples as return values

Functions can return tuples as return values. For example, we could
write a function that swaps two parameters:

def swap(x, y):
  return y, x


Then we can assign the return value to a tuple with two variables:

a, b = swap(a, b)


In this case, there is no great advantage in making swap a function.
In fact, there is a danger in trying to encapsulate swap, which is the
following tempting mistake:

def swap(x, y):      # incorrect version
  x, y = y, x


If we call this function like this:

swap(a, b)


then a and x are aliases for the same value. Changing xinside swap
makes x refer to a different value, but it has no effect on a in
__main__. Similarly, changing y has no effect on b.

This function runs without producing an error message, but it doesn't
do what we intended. This is an example of a semantic error.

As an exercise, draw a state diagram for this function so that you can
see why it doesn't work.

####################################################################

Thanks in Advance

Regards

Kaushal


More information about the Tutor mailing list