Change every box where it is
Double every value without making a new list. About 5 minutes.
Change the list you were given
Sometimes you're asked not to make a new list, but to change the one you have, like correcting marks on the same answer sheet instead of copying it onto a fresh one. That's called changing it in place. It saves memory, and a lot of interview questions ask for it.
To do it, write each new value straight back into the box it came from.
Box 0: read 3, double it, write 6 back into the same box.
You need the box number, not just the value
Here's a sneaky trap. A loop like "for each value in the list" hands you a copy of each value. Doubling the copy changes nothing in the list, like writing the corrected mark on a sticky note instead of on the sheet.
To write into a box you need its number. So loop over the box numbers and write through them.
for i in range(len(nums)):
nums[i] = nums[i] * 2
return numsThis runs on the list 1, 2. What does the list hold afterwards?
for value in nums: value = value * 2
- A1, 2
- B2, 4
- CAn error
Show the answer
1, 2. Each value is a copy. Doubling the copy doesn't touch the list.
Double in place
Double every value in the list, changing the list itself, and return it.
nums = [3, 1, 4, 2] → [6, 2, 8, 4]
0 ≤ n ≤ 1,000 · −1,000 ≤ each value ≤ 1,000