2

I have a question on the difference between just using max(list array) and np.max(list array).

Is the only difference here the time it takes for Python to return the code?

Steven Chiou
  • 21
  • 1
  • 2
  • Not exactly a duplicate, but relevant: https://stackoverflow.com/questions/10943088/numpy-max-or-max-which-one-is-faster – awesoon Jun 19 '18 at 03:49
  • Np.max is not intended to take a list array (it can). Look up ndarray, and after looking at the link in the comment above it will make sense. – Mario Ishac Jun 19 '18 at 04:00
  • 1
    What do you mean by "list array"? Python has lists. NumPy has arrays. They're different types. – Mark Dickinson Jun 19 '18 at 06:07

1 Answers1

2

They may differ in edge cases, such as a list containing NaNs.

import numpy as np
a = max([2, 4, np.nan])     # 4
b = np.max([2, 4, np.nan])  # nan

NumPy propagates NaN in such cases, while the behavior of Python's max is less certain.

There are also subtle issues regarding data types:

a = max([10**n for n in range(20)])     # a is an integer
b = np.max([10**n for n in range(20)])  # b is a float

And of course running time differences documented in numpy.max or max ? Which one is faster?

Generally, one should use max for Python lists and np.max for NumPy arrays to minimize the number of surprises. For instance, my second example is not really about np.max but about the data type conversion: to use np.max the list is first converted to a NumPy array, but elements like 10**19 are too large to be represented by NumPy integer types so they become floats.

  • I wouldn't recommend relying on the behaviour of Python's `max` with respect to NaNs. I suspect it's entirely an accident of the implementation. – Mark Dickinson Jun 19 '18 at 06:10
  • 1
    And indeed, `max(nan, 1.2)` is `nan`, not `1.2`. Python's `max` _doesn't_ explicitly ignore NaN entries; it's just that most of the time the comparison it's using internally goes the right way so that the `nan` doesn't get picked up as the max-so-far. – Mark Dickinson Jun 19 '18 at 07:12