OA. free
Free
MathWorks Data Structures & Algorithms Core Computer Science Medium

What is the expected output of evaluating the following Python code snippet?

MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.

What is the expected output of evaluating the following Python code snippet?

b = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(b[::3])
Choose one option.
Show answer & explanation
Answer: A. [0, 3, 6, 9]

The slice b[::3] uses Python's slice notation with a step of 3, starting from index 0 (default start) to the end (default stop). It returns every 3rd element: indices 0, 3, 6, and 9, corresponding to values [0, 3, 6, 9]. Option B incorrectly starts at index 2, option C returns only the first 4 elements, and option D returns a single element.

Step-by-step Derivation:
Python slice notation: b[start:stop:step]

  • b[::3] means: start=0 (default), stop=end (default), step=3
  • Begin at index 0: b[0] = 0
  • Add step 3: b[0+3] = b[3] = 3
  • Add step 3: b[3+3] = b[6] = 6
  • Add step 3: b[6+3] = b[9] = 9
  • Add step 3: b[9+3] = b[12] = out of bounds, stop
  • Result: [0, 3, 6, 9]