[Tutor] Example 2

Emil Styrke emil@lysator.liu.se
Wed Dec 11 21:04:02 2002


Adam Vardy <anvardy@roadrunner.nf.net> writes:

> Some ideas in Python are hard to follow. Is there a way to help
> configure your mind around it? Example:

Just keep on programming, and ask questions!

(In the following, I will assume that a function 'echo' exists, which
prints its argument to the screen)

> >>>
> >>> sch=[ (echo,'Spam!'), (echo,'Ham!') ]
> >>> for (func,arg) in sch:

This line is a short form for:

>>> for elem in sch:
>>>     (func, arg) = elem

The last line here, in turn, uses a concept called tuple
unpacking. It's equivalent to:

>>> func = elem[0]
>>> arg = elem[1]


> ...   apply(func, (arg,))

The apply function is a concept borrowed from functional programming
(e.g. Lisp).  It takes as arguments a function reference and a
sequence of arguments, and then it calls the function reference with
the argument sequence as arguments.

So, inside the loop, we have the variable func, which will contain the
first element of each tuple in the list sch, and another variable arg,
which will contain the second element of each tuple in the list.
Then, for each of these pairs, we call apply.  For example, the first
iteration of the loop will evaluate into

>>> apply(echo, ('Spam!',))

which will then call the function echo with the argument 'Spam!':

>>> echo('Spam!')

Hope that clears things up a little, for this particular case at
least!

        /Emil

> ...
> Spam!
> Ham!
> >>>
> 
> -- 
> Adam Vardy
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor