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?

1

2 Answers 2

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.

1
  • 2
    Also, lists of lists can store ragged data (lists of different lengths). Arrays are rectangular.
    – safetyduck
    Commented Sep 20, 2013 at 2:43
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).

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.