S2Q1 · Reversed Squares of List Elements¶
⚡ Quick Reference
Function: reversed_squares(l: list) -> list
Core idea: square each element of the reversed list (or reverse the list of squares - same result).
Key rules:
- Square each element: x**2
- Reverse order: iterate from last to first
- Empty list → return []
- reversed(l) iterates in reverse without modifying the original
Problem Statement¶
Problem
Write a function reversed_squares(l) that returns a new list of squares of the elements in reverse order.
Examples:
[1, 2, 3, 4, 5]
[25, 16, 9, 4, 1]
[10, 2]
[4, 100]
[-2, 5]
[25, 4]
Tracing both examples¶
[1, 2, 3, 4, 5]:
[10, 2]:
[-2, 5]:
Solution approaches¶
l[::-1] creates a reversed copy; the comprehension then squares each element.
Square all elements first, then reverse the result. Mathematically equivalent - squaring and reversing are independent operations.
Key takeaways¶
reversed() vs [::-1] - both work, different trade-offs
reversed(l) returns an iterator - no extra list created. l[::-1] creates a full reversed copy first. For a list comprehension, either is fine; reversed() is slightly more memory-efficient.
Square then reverse = reverse then square
Since squaring each element is independent of the order, [x**2 for x in l][::-1] gives the same result as [x**2 for x in reversed(l)]. Both are correct - pick whichever reads more naturally.
Negative numbers square to positive
(-2)**2 = 4. Squaring always produces a non-negative result. No special case needed for negative inputs.