![]() |
VOOZH | about |
While working with NumPy, you may notice that some operations return a copy, while others return a view. A copy creates a new, independent array with its own memory, while a view shares the same memory as the original array. As a result, changes made to a view also affect the original and vice versa.
A view lets you access the same data without making a copy. Changes made in the view affect the original array and vice versa, because they share memory. This makes views memory-efficient for working with large datasets. They’re known as shallow copies and can be created using the .view() method.
Example: Making a view and changing the original array
Original ID: 140055608657072 View ID: 140055066322448 Original array: [12 4 6 8 10] View array: [12 4 6 8 10]
Explanation: A NumPy array arr is created and a view v is made using .view(). Though they have different IDs, they share the same data, so changes in arr (like arr[0] = 12) also appear in v.
A copy creates a new, independent array with its own memory. Any change to the copied array won’t affect the original one, and vice versa. This is useful when you want to modify data safely without touching the original. A copy is also called a deep copy and can be created using the .copy() method.
Example: Making a copy and changing the original array
Original ID: 139627060167856 Copy ID: 139626512262672 Original array: [12 4 6 8 10] Copy array: [ 2 4 6 8 10]
Explanation: Here, c is a deep copy of arr. They have different object IDs and separate memory. When we update arr[0], it has no effect on c. This confirms that a copy is fully independent of the original array.
When you assign an array to another variable using =, you're not creating a copy or a view. You're just creating a new reference (alias) to the same array. Both variables point to the same data, so changes made through one will appear in the other.
Example: Assigning Array to Variable and changing Variable
Original ID: 140412154135824 Assigned ID: 140412154135824 Original array: [12 4 6 8 10] Assigned array: [12 4 6 8 10]
Explanation: nc is not a new object, it just points to the same data as arr. Their IDs are the same. Changing nc[0] to 12 also changes arr[0], because they’re the same array under different names.
In NumPy, you can check whether an array is a view or a copy using the .base attribute.
Example: Check if the array is a view or copy
None [ 2 4 6 8 10]
Explanation: