Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
A student wants to set the first two marks of a copy to zero, and writes this.
The student expected [5 6 7 8]. What does the program print, and why? Change the program so that marks does not change.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. A slice of an array is a view of the same numbers, not a copy. Writing into the slice writes into marks.
The program prints [0 0 7 8]. The slice first is a window on the places 0 and 1 of marks, and first[:] = 0 puts zero in both.
The fix is to ask for a real copy.
Check. Now first is its own array. marks stays [5 6 7 8] and first is [0 0].
Answer: [0 0 7 8], because the slice is a view. Use .copy().
Log in to join the discussion.
Loading…