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?

peco
  • 1,411
  • 3
  • 17
  • 38

3 Answers3

6

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

Community
  • 1
  • 1
Crispin
  • 2,070
  • 1
  • 13
  • 16
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

Community
  • 1
  • 1
Shivkumar kondi
  • 6,458
  • 9
  • 31
  • 58
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
Christian
  • 1,341
  • 1
  • 16
  • 35
ibezito
  • 5,782
  • 2
  • 22
  • 46