Start learning free

LESSON 268 OF 673 · TUPLES, SORTING & BUILT-INS

Squares of the Positives in Python: Map and Filter

Practice Read the full explanation

You get a list of integers, nums.

Return a new list with the square of every number above 0. A number's square is the number times itself.

Keep the squares in the order of their numbers in nums.

Leave out 0 and the negative numbers. If no number is above 0, return an empty list.

 

Example 1:

Input: nums = [3, -1, 0, 4]
Output: [9, 16]
Explanation: Only 3 and 4 are above 0.
3 times 3 is 9, and 4 times 4 is 16.

Example 2:

Input: nums = [-5, -2, 0]
Output: []
Explanation: No number is above 0.

Example 3:

Input: nums = [1, 2, 3]
Output: [1, 4, 9]
Explanation: Every number is above 0, so every number is squared.

 

Constraints:

  • nums may be empty.
  • Every number is between -1000 and 1000.
STEP 1 OF 2
    Ctrl + Enter to check

    PYTHON · TUPLES, SORTING & BUILT-INS

    Positive Squares in Python, explained

    Problem overview

    The method positiveSquares gets a list nums of integers and returns a new list with the square of every number above 0, in the original order. Zero and negative numbers are left out. If no number is above 0, or the list is empty, the answer is the empty list.

    For [3, -1, 0, 4] the answer is [9, 16]. Only 3 and 4 are above 0, and their squares are 9 and 16.

    Approach

    Two things happen to the numbers: some are dropped (a filter), and the rest are changed (a map). A list comprehension holds both in one line. The if at the end decides which numbers get in, and the front part says what each accepted number becomes.

    The order of work matters. The if runs first, on the original number, so negative numbers never get squared. This is important because a square is never negative: if you squared everything first, -1 would become 1 and could not be told apart from a real 1.

    Step by step

    1. Build squares with one comprehension: num * num for each num in nums, with if num > 0 at the end.
    2. Return squares.

    The solution in Python

    class Solution:
        def positiveSquares(self, nums: List[int]) -> List[int]:
            squares = [num * num for num in nums if num > 0]
            return squares
    

    The condition is num > 0, strict, so 0 is left out as the statement asks. When nothing passes, the comprehension builds an empty list, and that is the right answer, so no special case is needed. The same holds for an empty input list.

    Testing

    [3, -1, 0, 4]  ->  [9, 16]
    [-5, -2, 0]    ->  []
    [1, 2, 3]      ->  [1, 4, 9]
    []             ->  []
    

    Without the if, the first list would give [9, 1, 0, 16]: every number squared, including the ones that should be left out.

    Why a comprehension fits

    The same result needs four lines with a loop: make an empty list, loop over nums, test num > 0, append num * num. The loop is a fine answer too. The comprehension is worth learning because "keep some, change them" is such a common job, and reading it as "squares of the numbers above 0" is close to how you would say it aloud. The numbers are between -1000 and 1000, so the squares are at most a million, which Python holds without any overflow concern.

    Squaring with another operator

    You could also write num ** 2 for the square; num * num and num ** 2 give the same integer. The lesson writes num * num, the statement's own definition of a square: "the number times itself". Whichever you choose, keep it inside the front part of the comprehension and leave the condition alone.

    Common mistakes

    • Using num >= 0, which keeps 0 and adds a 0 to the result.
    • Putting the if in front of the for. A comprehension with a filter has the form [value for item in items if condition]; if at the front needs an else and does something else.
    • Returning None or printing when nothing passes. The answer is an empty list.
    • Changing nums in place. The method returns a new list.
    Keep going with Python500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free