v9.1.1
Menu

Basic Indexing

easyFREEIndexing & SlicingNumPy IndexingNumPy Foundations

Problem Statement

Access elements from a NumPy array using basic indexing.

Background

NumPy supports powerful indexing:

  • arr[i] - single element
  • arr[i, j] - element at row i, column j (for 2D)
  • Negative indices count from end

Your Task

Write a function get_elements(arr) that returns a dictionary with:

  • "first": First element (as int)
  • "last": Last element (as int)
  • "middle": Middle element (use len//2 for index, as int)

Output Format

Return a dictionary with exactly these three keys.

Example

Input
[10, 20, 30, 40, 50]
Output
{'first': 10, 'last': 50, 'middle': 30}
Reasoning
  • Input: arr is a one-dimensional array of n=5n = 5 whole numbers, [10, 20, 30, 40, 50]. Positions are counted from 00, so they run 0,1,2,3,40, 1, 2, 3, 4.
  • First: the element at position 00 is 1010.
  • Last: the final position is n−1=4n - 1 = 4, which holds 5050. Counting backwards from the end, it is the 1st element from the right.
  • Middle: the middle position is ⌊n/2⌋=⌊5/2⌋=⌊2.5⌋=2\lfloor n/2 \rfloor = \lfloor 5/2 \rfloor = \lfloor 2.5 \rfloor = 2, which holds 3030. With an odd length this is the exact centre: two elements sit on each side of it.
  • Output: a dictionary with keys first, last and middle mapped to plain integers: {'first': 10, 'last': 50, 'middle': 30}.
  • Notice what happens with an even length such as [100,200][100, 200]: ⌊2/2⌋=1\lfloor 2/2 \rfloor = 1, so the middle is 200200, the later of the two central values, and it equals the last element. For a one-element array, all three keys hold the same number.

Constraints

  • Use standard indexing arr[i]
  • Use negative indexing for last element
  • Array will have at least 1 element

Learn this in

More from NumPy Foundations

solution.py

Test results

Sign in to run your code against the test cases.