Reputation: 3
I tried to map the function math.pow
with the power of 2 to a list,
but the problem is that I should pass an iterable not just a single value.
So, I fixed it this way, by making a list of 2s with the same length as my list:
import math
lis = [1,2,3,4]
squred_lis = list(map(math.pow, lis, [2,2,2,2]))
print (squred_lis)
So, is there a way I can just pass a single value and have it passed every iteration as the second argument?
Upvotes: 0
Views: 464
Reputation: 6908
I think what you're looking for is itertools.repeat()
. It will repeat the value infinitely, and map()
will iterate as many of them as necessary to match the length of lis
.
import math
import itertools
lis = [1,2,3,4]
squared_lis = list(map(math.pow, lis, itertools.repeat(2)))
print(squared_lis)
which produces:
[1.0, 4.0, 9.0, 16.0]
Upvotes: 1
Reputation: 104
I think this is what you want
squred_lis = list(map(math.pow, lis, [2 for _ in range(len(a))]))
but.. how about this?
squared_list = list(map(lambda x: x ** 2, a))
Upvotes: 0