Labs ICT
โญ Pro Login

Copies vs Views

The gotcha that trips up every beginner.

2 min read | NumPy Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Copies vs Views

This is one of the trickiest parts of NumPy. Think of it like sharing a document - is it a link to the same file, or a separate copy?

Views Share Data

Many NumPy operations return views, not copies. Changes to the view affect the original array.


import numpy as np

original = np.array([1, 2, 3, 4, 5])
view = original[1:4]

print(f"Original: {original}")
print(f"View: {view}")

view[0] = 99
print(f"Modified view: {view}")
print(f"Original changed: {original}")
    

See that? Changing the view changed the original! That's because view is just a different way to look at the same data.

Copies Are Independent

Use copy() to create an independent copy.


import numpy as np

original = np.array([1, 2, 3, 4, 5])
copy = original.copy()

copy[0] = 99
print(f"Original: {original}")
print(f"Copy: {copy}")
    

Here is the thing - copy() uses more memory because you're duplicating data. But sometimes you need that independence.

How to Tell If It's a View

Check the base attribute. If it's None, it's an independent array.


import numpy as np

original = np.array([1, 2, 3])
view = original[:]
copy = original.copy()

print(f"View base: {view.base}")
print(f"Copy base: {copy.base}")
    

One thing that confused me at first was reshaping. reshape() usually returns a view, but flatten() returns a copy.

Key Takeaways

  • Views share data with the original array
  • Copies are independent and use more memory
  • Many operations return views (slicing, reshape)
  • Use .copy() when you need independence

๐Ÿงช Quick Quiz

What is the difference between a copy and a view?