List Comprehension Master
Problem Statement
Use list comprehensions to transform data efficiently.
Background
List comprehensions provide a concise way to create lists:
[expression for item in iterable if condition]
Your Task
Write a function transform_list(numbers) that returns a dictionary with various transformations.
Output Format
Return a dictionary with:
- "squared": Each number squared
- "evens": Only even numbers
- "positive": Only positive numbers
- "doubled_evens": Even numbers doubled
- "abs_values": Absolute value of each number
Example:
[-3, -2, -1, 0, 1, 2, 3, 4]
{'squared': [9, 4, 1, 0, 1, 4, 9, 16], 'evens': [-2, 0, 2, 4], 'positive': [1, 2, 3, 4], 'doubled_evens': [-4, 0, 4, 8], 'abs_values': [3, 2, 1, 0, 1, 2, 3, 4]}List comprehensions with conditions filter and transform efficiently
Constraints:
- Use list comprehensions
- Preserve original order
Background Knowledge
List comprehensions in Python offer a compact, readable alternative to traditional loops for creating lists by applying transformations or filters to iterables. The syntax [expression for item in iterable if condition] processes each item from iterable, optionally filtering with condition, and collects expression results into a new list. This leverages Python's control flow implicitly: the for iterates sequentially, while if acts as a conditional filter evaluated per item. For this problem, understanding how to nest expressions (e.g., item * 2 if item % 2 == 0 else None) or chain conditions enables efficient data transformations without explicit loops.
Dictionaries in Python store key-value pairs, ideal for grouping related lists like transformations of a single input list. Keys are strings (e.g., "squared"), and values are lists generated via comprehensions. Absolute value (abs()), modulo (% 2 == 0 for evens), and comparisons (> 0 for positives) are built-in operations that fit naturally into comprehension expressions. Mastering these builds intuition for functional-style programming, reducing code verbosity while maintaining clarity.
Algorithm/Approach
Use dictionary construction with list comprehensions as values, where each key maps to a transformation of the input list numbers. Iterate over numbers once per transformation, applying the specific expression and optional filter. This one-pass per list pattern exploits list comprehensions' efficiency, avoiding mutable state or multiple loops. The output dictionary collects these independent transformations, ensuring order preservation from the input.
Step-by-Step Strategy
- Initialize the dictionary: Create an empty dict to hold the five keys.
- Generate each list:
- For "squared": Square every number.
- For "evens": Filter numbers where number % 2 == 0.
- For "positive": Filter numbers where number > 0.
- For "doubled_evens": Filter evens, then double them (combine filter and expression).
- For "abs_values": Apply abs() to every number.
- Assign to dictionary: Populate each key with its comprehension-derived list.
- Return the dictionary: Ensure all keys are present with correct list contents and order.
Test with the sample input to verify: negatives become positive in squares/abs, evens include negatives/zero, positives exclude zero/negatives.
Common Pitfalls
- Forgetting the if condition: Including odds in "evens" or zero/negatives in "positive".
- Order mismatch: Comprehensions preserve input order; don't sort unless specified.
- Operator precedence: Use parentheses for complex expressions like (item ** 2 if condition else 0), though simple cases like item * 2 are fine.
- Empty input: Handle [] gracefully—each list should be empty, dictionary intact.
- Mutability: Don't modify numbers; create new lists to avoid side effects.
- Syntax errors: Missing colons or incorrect if placement (must follow for, not prefix expression).
Time & Space Complexity
- Time: O(5n)=O(n), where n is list length—five independent O(n) comprehensions.
- Space: O(5n)=O(n) for output lists; temporary per comprehension, no recursion. Python's list building is efficient, but large n (e.g., 106) uses memory linearly.