v9.1.1
Menu

List Comprehension Master

easyFREEControl FlowPython ComprehensionsPython Foundations

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

Input
[-3, -2, -1, 0, 1, 2, 3, 4]
Output
{'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]}
Reasoning
  • numbers is a list of eight integers, [-3, -2, -1, 0, 1, 2, 3, 4]. Each output list keeps the input's left-to-right order.
  • squared sends each xx to x2x^2: (−3)2=9(-3)^2 = 9, (−2)2=4(-2)^2 = 4, (−1)2=1(-1)^2 = 1 … up to 42=164^2 = 16. Numbers of equal size but opposite sign give the same square.
  • evens keeps only the xx that leave remainder 00 when divided by 22: −2,0,2,4-2, 0, 2, 4. Zero and negative evens both count.
  • positive keeps the strictly positive values (x>0x > 0), so 00 is left out: [1, 2, 3, 4].
  • doubled_evens uses the same filter as evens and then sends each kept xx to 2x2x: −2→−4-2 \to -4, 0→00 \to 0, 2→42 \to 4, 4→84 \to 8.
  • abs_values sends each xx to ∣x∣|x|, giving [3, 2, 1, 0, 1, 2, 3, 4].
  • Notice that the transformed lists keep all 8 entries but the filtered ones are shorter. An input with no positives, such as −5,−4,−3-5, -4, -3, gives an empty positive list.

Constraints

  • Use list comprehensions
  • Preserve original order

Learn this in

More from Python Foundations

solution.py

Test results

Sign in to run your code against the test cases.