0

I am new to Python and I have done a fair share of just trying things to see if it works. In this case, when I apply a Callable to an NDArray, I get a result, just not what I expected.

from typing import Callable
from typing import Tuple
import numpy as np

callable : Callable[[float], Tuple[float, float]] = lambda x : (x , x + 1)
array : np.ndarray = np.asarray([0, 1, 2, 3])
result = callable(array)
print(result)

I expected (or rather hoped) to get an iterable of tuples where each tuple is the output of the callable applied to a float. What I got was a tuple of arrays:

(array([0, 1, 2, 3]), array([1, 2, 3, 4]))

What is actually happening? (Why should I expect the results I actually got?)

Little Endian
  • 784
  • 8
  • 19
  • 1
    That `lambda` function does not iterate on `array`. The `x` inside the function is `array` itself, the whole thing. It just returns a tuple, the same as if you did `result=(array, array+1)`. Using the `lambda` does not change that behavior. Your `lambda` is just another syntax for doing `def foo(x): return x, x+1`. – hpaulj May 02 '23 at 15:55
  • If you want to iterate, you'll have to iterate. `callable(x)` is just calling your function on object `x`. It doesn't "apply" anything in the sense that you want – Mad Physicist May 02 '23 at 15:58
  • 2
    I think you want `map(callable, array)`. – Quang Hoang May 02 '23 at 15:59
  • 1
    Also, your typing annotation is just misleading. – Mad Physicist May 02 '23 at 15:59

1 Answers1

0

To summarize the comments, the typing annotation for callable was misleading and the lambda was just applied to the array itself - the same as if I did result=(array, array+1). Nothing mysterious going on. Thanks for the help.

Little Endian
  • 784
  • 8
  • 19