1

After only briefly looking at numpy arrays, I don't understand how they are different than normal Python lists. Can someone explain the difference, and why I would use a numpy array as opposed to a list?

Scott Tesler
  • 39,441
  • 4
  • 25
  • 20
  • 3
    How about taking more than a "brief" look? Here is the first hit for a "why numpy" google search: http://stackoverflow.com/questions/993984/why-numpy-instead-of-python-lists – roippi Sep 20 '13 at 02:45

2 Answers2

5

NumPy arrays are specifically designed for working with multidimensional numeric data, with additional support for arrays of arbitrary objects. They provide fast vectorized operations with convenient syntax.

>>> x = numpy.arange(4).reshape((2, 2))
>>> x
array([[0, 1],
       [2, 3]])
>>> x.T           # Transpose.
array([[0, 2],
       [1, 3]])
>>> x.max()
3
>>> x * 4
array([[ 0,  4],
       [ 8, 12]])
>>> x[:, 1]       # Slice to select the second column.
array([1, 3])
>>> x[:, 1] *= 2
>>> x
array([[0, 2],
       [2, 6]])
>>> timeit.timeit('x * 5',
...               setup='import numpy; x = numpy.arange(1000)',
...               number=100000)
0.4018515302670096
>>> timeit.timeit('[item*5 for item in x]',
...               setup='x = range(1000)',
...               number=100000)
8.542360042395984

In comparison, lists are fundamentally geared towards 1-dimensional data. You can have a list of lists, but that's not a 2D list. You can't conveniently take the max of a 2D data set represented as a list of lists; calling max on it will compare the lists lexicographically and return a list. Lists are good for homogeneous sequences of objects, but if you're doing math, you want numpy, and you want ndarrays.

user2357112
  • 260,549
  • 28
  • 431
  • 505
0

Numpy is an extension, and demands that all the objects on it are of the same type , defined on creation. It also provides a set of linear algebra operations. Its more like a mathematical framework for python to deal with Numeric Calculations (matrix, n stuffs).

Sinn
  • 274
  • 1
  • 7