Home > Blockchain >  Passing one value along with a list to a map in python
Passing one value along with a list to a map in python

Time:10-23

I tried to map the function math.pow with the power of 2 to a list but the problem that i should pass iterable not just a single value So Fixed this way, by making a list of 2s with the same lenght 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 a can just pass a single value and it passed every iteration as the second argument?

CodePudding user response:

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))

CodePudding user response:

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]
  • Related