Positions start at 0
Read the first and last values. About 4 minutes.
Open a box by its number
An array keeps values in a row of numbered boxes. The number of a box is its index, and it starts at 0. To read a
box, write the array's name with the index in square brackets: nums[0] is the first value.
That's why reading any box is instant, however long the array is. The computer doesn't search: it goes straight to box 3, the way you'd walk straight to locker 3.
Box 0 holds 7, the first value. In code that's nums[0].
The last box is one less than the length
The length is how many boxes there are. With 5 boxes numbered from 0, the numbers are 0, 1, 2, 3 and 4. So the last box is always the length minus one.
Asking for box 5 in a row of 5 is asking for a locker that isn't there. Depending on the language you'll get an error or a strange value, so it's worth getting this right early.
first = nums[0] last = nums[len(nums) - 1] return [first, last]
The array holds 8, 3, 6. What's in box 2?
- A8
- B3
- C6
- DThere is no box 2
Show the answer
6. Box 2 is the third box, and it holds 6.
First and last
You get a list with at least one number in it. Return a list of two values: the first number, then the last number.
nums = [7, 2, 9, 4, 5] → [7, 5]
1 ≤ n ≤ 100 · with one number, it is both the first and the last