Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a lambda with a numpy array

While familiarizing myself with numpy, I noticed an interesting behaviour in numpy arrays:

import numpy as np

arr = np.array([1, 2, 3])
scale = lambda x: x * 3

scale(arr) # Gives array([3, 6, 9])

Contrast this with normal Python lists:

arr = [1, 2, 3]
scale = lambda x: x * 3

scale(arr) # Gives [1, 2, 3, 1, 2, 3, 1, 2, 3]

I'm curious as to how this is possible. Does a numpy array override the multiplication operator or something?

like image 619
peco Avatar asked Mar 21 '17 07:03

peco


People also ask

Can I apply a function to a NumPy array?

We can map a function over a NumPy array just by passing the array to the function.

Can we call lambda function in Python?

A Python lambda function behaves like a normal function in regard to arguments. Therefore, a lambda parameter can be initialized with a default value: the parameter n takes the outer n as a default value. The Python lambda function could have been written as lambda x=n: print(x) and have the same result.

Can you use SymPy and NumPy together?

In general, SymPy functions do not work with objects from other libraries, such as NumPy arrays, and functions from numeric libraries like NumPy or mpmath do not work on SymPy expressions.


1 Answers

numpy.ndarray overloads the * operator by defining its own __mul__ method. Likewise for +, -, etc. This allows for vector arithmetic.

like image 82
Crispin Avatar answered Sep 21 '22 17:09

Crispin