4

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

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You could also use map(power, list, itertools.repeat(2, len(list))) to avoid creating a second list.
If you wanted to be ultra-fancy, you could use itertools.cycle([2]) instead of [2]*len(list).
3
import math
power = lambda n: lambda x: math.pow(x,n)
list = [1,2,3,4,5]
map(power(2),list)

Comments

3

Like this:

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

Comments

3

List comprehensions are another option:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.