Referring to a list

Dave Kuhlman dkuhlman at rexx.com
Fri Jun 25 19:22:11 EDT 2004


Russell Blau wrote:

[snip]

> 
> Does this help?
> 
>>>> odd_list = []
>>>> even_list = []
>>>> def which_list(x):
>       if x % 2 == 0:
>           return even_list
>       else:
>           return odd_list
> 
>>>> for i in range(20):
>       which_list(i).append(i)
> 
> 
>>>> odd_list
> [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>>> even_list
> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
> 
> 

Basically, what this and other replies to your question are
telling you is that lists in Python are first-class objects.  To
be a first-class object means that you can (1) stuff it into a
data structure (for example, a dictionary or another list), pass
it in to a function, and (3) return it as the value of a function.

Also remember that functions in Python are first class, so you do
something like this:

def do_job(arg, listarg, even_func, odd_func):
    if arg % 2 == 0:
        even_func(arg, listarg)
    else:
        odd_func(arg, listarg)

That makes doing delegation in Python easy and natural.  OK. OK.
It's not natural, but it's about as natural as something as weird
as computer programming is going to get.

Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman



More information about the Python-list mailing list