12

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?

2
  • This has nothing to do with lambda... anyway, numpy arrays override most operators to perform vectorized operations. That's one of the key features of numpy... Commented Mar 21, 2017 at 7:47
  • see docs.scipy.org/doc/numpy-dev/user/… Commented Mar 21, 2017 at 7:49

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

6

Its all about Overriding operators in numpy

You can learn numpy.arry here

Let us focus on your lamda function for each;

1. numpy array :

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

this takes each element from array

2. normal list:

a =[1,2,3]
type(a)
scale = lambda x: x * 3 
scale(a)

this takes full list as x and multiplies the list here itself

Comments

1

These are two different objects which behaves differently when you use * operator on them.

  1. In the first case you generate a numpy array. In this case, * operator was overloaded for performing multiplication. i.e. every element will be multiplied by 3.

  2. In the second case you generate a list. In this case the * operator is treated as a repetition operator, and the entire list is repeated 3 times.

code example:

type(np.array([1,2,3]))
type([1, 2, 3])

result:

numpy.ndarray
list

2 Comments

I think the types are reversed
I now fixed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.