Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

New Array of Squares

Create a separate list of squares with append. Students preserve original values, transform every element once, and compare the two displayed lists afterward.

IntermediatePhase 4 - Level 3: TransformationExample 1 of 10
new-array-of-squares.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7# Create new array of squares
8squared_arr = []
9for element in arr:
10 squared_arr.append(element * element)
11
12print(f"Original: {arr}")
13print(f"Squared: {squared_arr}")

Output

Enter array size: 4
Element 1: 2
Element 2: 3
Element 3: 4
Element 4: 5
Original: [2, 3, 4, 5]
Squared: [4, 9, 16, 25]

In this one

  • Transform into a new list
  • Square signed values
  • Retain source data

How it works

  1. 1

    Create squared_arr separately from arr.

  2. 2

    Append element * element for every source value.

  3. 3

    Print the original and transformed lists.

Edge cases

What happens to negative values?

What happens to negative values?

Their squares are nonnegative.

What if arr is empty?

What if arr is empty?

Both displayed lists are empty.

What's going on

squared_arr starts as a new empty list. For each element in arr, the code appends element * element.

The source list is not assigned through an index, so its original values remain available for the first print. The new list has the same number of elements in the same positional order, but contains squared values rather than copies of the original integers.

What happens to negative values? Their squares are nonnegative.

What if arr is empty? Both displayed lists are empty.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Is arr modified?

Pick an answer to check it.

Question 2

What happens to negative values?

Pick an answer to check it.

Questions people ask

What happens to negative values?

Their squares are nonnegative.

What if arr is empty?

Both displayed lists are empty.

Is arr modified?

No.