Say I have
a = [1,2,3]
b = [foo(x) for x in a]
Now b is something like [ < function at 0x00F91540>, …], how do I get python to evaluate b into it’s actual values?
–EDIT–
Sorry for the confusion, my frustration is that Python doesn’t give me the actual values in b, hence when I try to do something like:
b[0] + 1
it gives me the below error:
TypeError: unsupported operand type(s) for +: 'function' and 'int'
Define your function outside the comprehension:
Now,
b == [2,3,4]. Or, as others have pointed out, just use the function body in the list comprehension:…although this assumes that you can reproduce the function body in this way (which you won’t be able to do for more complicated functions).
Note that the result of a
lambdaexpression is the same as typing the name of a function, eg.lambda x: x+1andfoorepresent the same thing: a function which needs a parameter given to it and returns a result. For the sake of clarification, this is how you’d “use” a lambda in a list comprehension:…but seriously, don’t do this 😉