NumPy views: saving memory, leaking memory, and subtle bugs

If you’re using Python’s NumPy library, it’s usually because you’re processing large arrays that use plenty of memory.
To reduce your memory usage, chances are you want to minimize unnecessary copying,

NumPy has a built-in feature that does this transparently, in many common cases: memory views.
However, this feature can also cause higher memory usage by preventing arrays from being garbage collected.
And in some cases it can cause bugs, with data being mutated in unexpected ways.

To avoid these problems, let’s learn how views work and the implications for your code.

Preliminary: Python lists

Before looking at NumPy arrays and views, let’s consider a somewhat similar data structure: Python lists.

Python lists, like NumPy arrays, are contiguous chunks of memory.
When you slice a Python list,

 

 

 

To finish reading, please visit source site