liv2hak
liv2hak

Reputation: 14970

defining a lambda function with two arguments

I have some code as shown below.

import math
square_root = lambda x: math.sqrt(x)
list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
map(square_root,list)

Output:

[1.0,
 1.4142135623730951,
 1.7320508075688772,
 2.0,
 2.23606797749979,
 2.449489742783178,
 2.6457513110645907,
 2.8284271247461903,
 3.0,
 3.1622776601683795,
 3.3166247903554,
 3.4641016151377544,
 3.605551275463989,
 3.7416573867739413,
 3.872983346207417,
 4.0]

Now I want to use power instead of square_root

import math
power = lambda x: math.power(x,n)
list = [1,2,3,4,5]
map(power,list,2)

And I get the following error? How do I use two arguments with map?

TypeError Traceback (most recent call last) /home/AD/karthik.sharma/ws_karthik/trunk/ in () ----> 1 map(power,list,2)

TypeError: argument 3 to map() must support iteration

Upvotes: 4

Views: 12898

Answers (4)

rpb
rpb

Reputation: 81

List comprehensions are another option:

list = [1,2,3,4,5]
[math.pow(x,2) for x in list]

Upvotes: 3

nakedfanatic
nakedfanatic

Reputation: 3158

Like this:

power = lambda x, n: math.pow(x,n)
list = [1,2,3,4,5]
map(lambda x: power(x, 2), list)

Upvotes: 3

R Sahu
R Sahu

Reputation: 206577

import math
power = lambda n: lambda x: math.pow(x,n)
list = [1,2,3,4,5]
map(power(2),list)

Upvotes: 2

Greg Hewgill
Greg Hewgill

Reputation: 993055

One way to do this is the following:

power = lambda x, n: math.pow(x,n)
list = [1,2,3,4,5]
map(power,list,[2]*len(list))

The expression [2]*len(list) creates another list the same length as your existing one, where each element contains the value 2. The map function takes an element from each of its input lists and applies that to your power function.

Another way is:

power = lambda x, n: math.pow(x,n)
list = [1,2,3,4,5]
map(lambda x: power(x, 2),list)

which uses partial application to create a second lambda function that takes only one argument and raises it to the power 2.

Note that you should avoid using the name list as a variable because it is the name of the built-in Python list type.

Upvotes: 8

Related Questions