beoliver - 8 months ago 40

Python Question

Take for example the python built in

`pow()`

`xs = [1,2,3,4,5,6,7,8]`

from functools import partial

list(map(partial(pow,2),xs))

>>> [2, 4, 8, 16, 32, 128, 256]

but how would I raise the xs to the power of 2?

to get

`[1, 4, 9, 16, 25, 49, 64]`

`list(map(partial(pow,y=2),xs))`

TypeError: pow() takes no keyword arguments

I know list comprehensions would be easier.

Answer

According to the documentation, `partial`

*cannot* do this (emphasis my own):

partial.argsThe

leftmostpositional arguments that will be prepended to the positional arguments

You could always just "fix" `pow`

to have keyword args:

```
_pow = pow
pow = lambda x, y: _pow(x, y)
```