>
> * How is the syntax for calling a lambda expression with arguments?
>
> I.e. what is the python equivalent of the following Scheme expression?
>
> ((lambda (n) (+ n 1)) 10)
>
> I actually tried that in the context of converting a list to tuple
> and I tried to get something like that to work
>
> lambda l: l[0], l[1] ( [1, 2] )
>
> and many variants thereof but couldn't find one that worked.
You came up with a good one there!
Problem #1: First of all, you need to use:
>>>lambda l: ( l[0], l[1] ) # which yields:
<anonymous function at 20068eb8>
Without the parends around the tuple, the expression is ambiguous
and is in fact, interpreted as: (lambda l: l[0]),(l[1])
>>> lambda l: l[0], l[1]
Traceback (innermost last):
File "<stdin>", line 1
NameError: l
Name error here makes that clear, but if you first assign something
to l, that will mask the error somewhat.
>>> l = [1,2]
>>> lambda l: l[0], l[1]
(<anonymous function at 20071948>, 2)
"somewhat" - meaning, it's obvious if you look at the above return
value, but if you just try to apply that tuple as a function, the
error returned may be confusing.
Problem #2: There must be a bug in the parser (Guido?), because:
>>> lambda l: (l[0], l[1] )([1,2]) # just yields the function
<anonymous function at 20071a08>
And it looks like you have to wrap parends around the lambda expression
to get it to be applied:
>>> (lambda l: (l[0], l[1] ))([1,2])
(1, 2)
- or, alternatively:
>>> apply( lambda l: (l[0], l[1] ), ([1,2],) )
(1, 2)
[Note also the comma, to make ([1,2],) into a single tuple of a list.]
>
> Alternatively is there a way (other than writing it in python) to
> convert from a tuple to a list and vice versa? There are such
> operations for the array type, at least you can fill an array
> from a list and convert the array to a list.
>
I'll repost last months list of conversion tricks:
( When this was last discussed, I think Guido said that he *would*
be putting a tuple() and perhaps a list() builtin in a later release.
If you want to define a tuple() function in python, the last
example is probably one of the least effecient ways to do it.
It's in there because it's the least verbose. )
>>> string.joinfields( ['a', 'b', 'c', 'd', 'e'], '' ) # list to string
'abcde'
>>> map( None, 'abcdefg' ) # string to list
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> map( None, ( 1,2,3,4,5,6 ) ) # tuple to list
[1, 2, 3, 4, 5, 6]
>>> map( None, [1,2,3], [10,20,30], [100,200,300] ) # transpose
[(1, 10, 100), (2, 20, 200), (3, 30, 300)]
>>> reduce( lambda a,b: a + (b,), 'abcdefg', ()) # string to tuple
('a', 'b', 'c', 'd', 'e', 'f', 'g')
>>> reduce( lambda a,b: a + (b,), [1,2,3,4,5], () ) # list to tuple
(1, 2, 3, 4, 5)
- Steve Majewski (804-982-0831) <sdm7g@Virginia.EDU>
- UVA Department of Molecular Physiology and Biological Physics