v9.1.1
Menu

List Operations

easyFREELists & DictionariesPython ListsPython Foundations

Problem Statement

Perform common list operations.

Background

Python lists support many operations:

  • Append: lst.append(item)
  • Extend: lst.extend([items])
  • Insert: lst.insert(index, item)
  • Remove: lst.remove(item)
  • Pop: lst.pop(index)
  • Slice: lst[start:end]

Your Task

Write a function list_stats(numbers) that computes statistics about a list of numbers.

Output Format

Return a dictionary with:

  • "length": Number of elements
  • "sum": Sum of all elements
  • "min": Minimum value
  • "max": Maximum value
  • "first_three": First 3 elements as list
  • "last_three": Last 3 elements as list
  • "sorted": Sorted list (ascending)

Example

Input
[5, 2, 8, 1, 9, 3]
Output
{'length': 6, 'sum': 28, 'min': 1, 'max': 9, 'first_three': [5, 2, 8], 'last_three': [1, 9, 3], 'sorted': [1, 2, 3, 5, 8, 9]}
Reasoning
  • Input: numbers is a list of six integers, [5, 2, 8, 1, 9, 3]. Positions run 11 to nn with n=6n = 6.
  • Size and total: there are n=6n = 6 elements, so length is 6. Adding them gives 5+2+8+1+9+3=285 + 2 + 8 + 1 + 9 + 3 = 28, the sum.
  • Extremes: the smallest is 11 (position 4) and the largest is 99 (position 5), so min is 1 and max is 9.
  • Portions: first_three takes positions 11–33, giving [5, 2, 8]; last_three takes positions n−2n-2 to nn, i.e. 44–66, giving [1, 9, 3]. Both keep the original input order.
  • Ordering: arranging all six values from smallest to largest gives [1, 2, 3, 5, 8, 9] for the sorted key; its ends match min and max.
  • Notice: the two portions only stay separate when n≥6n \ge 6, as here. For n=3n = 3 both are the whole list; for 3<n<63 < n < 6 they share positions, e.g. [10, 20, 30, 40, 50] has 30 in both.

Constraints

  • List will have at least 3 elements
  • All elements are integers

Learn this in

More from Python Foundations

solution.py

Test results

Sign in to run your code against the test cases.