Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Introduction to NumPy Array Organization Slicing

I modified a slice of ndarray and this also modified the original array. Why is it contrary to what we see in the video?

In the video, modifying the copied array did not change the fruits array. When I practice modifying a slice of an array, the original array was modified. In addition, answering one of the quiz questions based on the video will give a wrong answer. Is there something I am missing?

Cheo R
Cheo R
37,150 Points

Can you post your code?

fruits = np.array(['orange', 'guava', 'grape'])
copied = fruits[1:]
copied[0] = 'berry'
fruits, copied

Output:

(array(['orange', 'berry', 'grape'], dtype='<U6'),
 array(['berry', 'grape'], dtype='<U6'))
Cheo R
Cheo R
37,150 Points

It looks like you're returning a view and not a copy. Rewatch the video starting at 8:10 where he explains the difference.

1 Answer

When you say that

In the video, modifying the copied array did not change the fruits array.

you are probably referring to the time around minute 04:14. Note that in that case, it was a list. Slicing a list will return a copy but slicing an ndarray as explained around minute 8:13 will return only a view.

If you were testing out slicing lists, the proper command should have been

fruits = ['orange', 'guava', 'grape']
copied = fruits[1:]
copied[0] = 'berry'
fruits, copied

To get the desired output

(['orange', 'guava', 'grape'], ['berry', 'grape'])