List Operations
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:
[5, 2, 8, 1, 9, 3]
{'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]}len() for length, sum() for sum, min()/max() for extremes, slicing for portions
Constraints:
- List will have at least 3 elements
- All elements are integers
Background Knowledge
Python lists are mutable, ordered collections that store elements of any type, making them ideal for dynamic data manipulation. Key built-in methods like len(), sum(), min(), max(), and slicing (lst[start:end]) enable efficient computation of basic statistics without loops. For example, numbers[:3] extracts the first three elements, while sorted(numbers) returns a new sorted list in ascending order without modifying the original.
Dictionaries provide a natural structure for organizing key-value pairs, where keys are strings (e.g., "length") and values can be integers, lists, or other types. Returning a dict allows bundling multiple statistics into a single, structured output. Understanding immutability is crucial: operations like min() and sorted() create views or copies, preserving the original list.
These concepts build foundational skills in list traversal, aggregation, and data structuring—core to Python data analysis and preparing for libraries like NumPy or pandas.
Algorithm/Approach
Use Python's built-in functions for O(n) operations on lists to compute statistics directly, avoiding manual loops for efficiency. Construct a dictionary by mapping each required key to its computed value, leveraging slicing for sublists and sorting for ordered output.
This functional approach emphasizes readability: chain operations like slicing and aggregation, then populate the dict in one pass where possible.
Step-by-Step Strategy
- Compute scalar stats: Use len(numbers) for length, sum(numbers) for total, min(numbers) and max(numbers) for extremes.
- Extract sublists: Apply slicing—numbers[:3] for first three (handles short lists gracefully), numbers[-3:] for last three.
- Sort the list: Call sorted(numbers) to get an ascending copy.
- Build dictionary: Initialize an empty dict, assign each key-value pair using computed results.
- Edge cases: Test with empty lists (e.g., min([]) raises ValueError—handle if needed) and short lists (slicing returns fewer elements).
Common Pitfalls
- Modifying input: numbers.sort() mutates the original; use sorted(numbers) instead.
- Empty/short lists: min([]) or max([]) raises ValueError; numbers[:3] on a 1-element list returns [elem].
- Slicing bounds: numbers[-3:] works for len < 3, but verify output matches sample (truncates naturally).
- Dict key typos: Exact strings like "first_three" (underscores, not spaces/camelCase).
- Return type: Must return dict, not print; ensure lists in values are new copies.
Time & Space Complexity
- Time: O(n) overall—dominated by sum(), min(), max(), sorted() (all linear scans or n log n for sort, but n log n dominates for large n).
- Space: O(n) for sorted() copy and sublist slices (shallow copies); dict adds O(1) + O(n) for stored lists. Efficient for typical inputs.