13

Why do we use numpy arrays in place of lists in python? What is the main difference between them?

Mobi Zaman
  • 605
  • 1
  • 6
  • 19

1 Answers1

11

Numpy arrays is a typed array, the array in memory stores a homogenous, densely packed numbers.

Python list is a heterogeneous list, the list in memory stores references to objects rather than the number themselves.

This means that Python list requires dereferencing a pointer every time the code needs to access the number. While numpy array can be processed directly by numpy vector operations, which makes these vector operations much faster than anything you can code with list.

The drawback of numpy array is that if you need to access single items in the array, numpy will need to box/unbox the number into a python numeric object, which can make it slow in certain situations; and that it can't hold heterogeneous data.

Lie Ryan
  • 62,238
  • 13
  • 100
  • 144
  • 6
    This is true of a *list*, but not of an *array*, which also exists in the standard library. – jonrsharpe Mar 06 '16 at 10:49
  • 2
    So @jonrsharpe are you saying that normal python arrays and Numpy arrays are essentially equal? Please describe your comment a bit more. Thank you – Muhammad Muzammil Dec 29 '19 at 20:44
  • @MuhammadMuzammil I'm saying that a [list](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range) is not the same thing as an [array](https://docs.python.org/3/library/array.html); it's not clear to me which the OP meant by *"simple python array"*. – jonrsharpe Dec 29 '19 at 22:03