What are the advantages and disadvantages of storing Python objects in a numpy.array
with dtype='o'
versus using list
(or list
of list
, etc., in higher dimensions)?
Are numpy arrays more efficient in this case? (It seems that they cannot avoid the indirection, but might be more efficient in the multidimensional case.)
NumPy & Lists Originally known as 'Numeric,' NumPy sets the framework for many data science libraries like SciPy, Scikit-Learn, Panda, and more. While Python lists store a collection of ordered, alterable data objects, NumPy arrays only store a single type of object.
1. NumPy uses much less memory to store data. The NumPy arrays takes significantly less amount of memory as compared to python lists. It also provides a mechanism of specifying the data types of the contents, which allows further optimisation of the code.
List is used to collect items that usually consist of elements of multiple data types. An array is also a vital component that collects several items of the same data type. List cannot manage arithmetic operations. Array can manage arithmetic operations.
Because the Numpy array is densely packed in memory due to its homogeneous type, it also frees the memory faster. So overall a task executed in Numpy is around 5 to 100 times faster than the standard python list, which is a significant leap in terms of speed.
Slicing works differently with NumPy arrays. The NumPy docs devote a lengthy page on the topic. To highlight some points:
list
by assigning a sequence of different length to a slice, whereas NumPy would raise an error.Demo:
>>> a = np.arange(4, dtype=object).reshape((2,2))
>>> a
array([[0, 1],
[2, 3]], dtype=object)
>>> a[:,0] #multidimensional slicing
array([0, 2], dtype=object)
>>> b = a[:,0]
>>> b[:] = True #can assign scalar
>>> a #contents of a changed because b is a view to a
array([[True, 1],
[True, 3]], dtype=object)
Also, NumPy arrays provide convenient mathematical operations with arrays of objects that support them (e.g. fraction.Fraction
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With