A couple of quick questions

Alex alex at somewhere.round.here
Mon May 24 23:00:30 EDT 1999


> How about:
> 
> new_list = map(lambda x: list[x], indexes)

This is interesting.  It works when the variable "list" has been defined
in the global namespace, like when you're in interactive mode, but not
otherwise.

Python 1.5.1 (#1, Jan 31 1999, 18:55:21)  [GCC 2.8.1] on irix6
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> list = [1,2,3,4,5,6,7,8,9,10,11]
>>> indices = [3,5,9]
>>> new_list = map (lambda x: list [x], indices)
>>> new_list
[4, 6, 10]
>>> def global_name_space_hider ():
    	new_list = map (lambda x: list [x], indices)
    	return new_list
... ... ... 
>>> global_name_space_hider ()
[4, 6, 10]
>>> # Still works in a function.  But now try changing it to a locally
... # defined list.
... 
>>> def global_name_space_hider ():
        local_list = [1,2,3,4,5,6,7,8,9,10,11]
        local_indices = [3,5,9]
        new_list = map (lambda x: local_list, local_indices)
        return new_list
... ... ... ... ... 
>>> global_name_space_hider ()
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 4, in global_name_space_hider
  File "<stdin>", line 4, in <lambda>
NameError: local_list
>>> # To circumvent this, you need to push a reference to
... # local_list into the into the namespace of the lambda
... # function, or whatever the right terminology is. You
... # can do that by assigning it as a default value. e.g.:
... 
>>> def global_name_space_hider ():
        local_list = [1,2,3,4,5,6,7,8,9,10,11]
        local_indices = [3,5,9]
        new_list = map (lambda x, l = local_list: l [x], \
                        local_indices)
        return new_list
... ... ... ... ... ... 
>>> global_name_space_hider ()
[4, 6, 10]
>>> 

See you.
Alex.




More information about the Python-list mailing list