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

Replace Negatives with 0

Replace negative list entries with zero in Python. Students use indexes for in-place updates and distinguish changing an element from changing a loop variable.

IntermediatePhase 4 - Level 3: TransformationExample 3 of 10
replace-negatives-with-0.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# Replace negatives
8for i in range(len(arr)):
9 if arr[i] < 0:
10 arr[i] = 0
11
12print(f"Modified array: {arr}")

Output

Enter array size: 5
Element 1: 5
Element 2: -3
Element 3: 10
Element 4: -2
Element 5: 7
Modified array: [5, 0, 10, 0, 7]

In this one

  • Update through indexes
  • Change values in place
  • Keep list length fixed

How it works

  1. 1

    Visit valid indexes of arr.

  2. 2

    Test whether arr[i] is negative.

  3. 3

    Assign zero to that position only when true.

Edge cases

Does zero change?

Does zero change?

No. It is not negative.

Does an empty list cause an error?

Does an empty list cause an error?

No. There are no indexes to visit.

What's going on

The loop visits valid indexes, not just values. When arr[i] is negative, assigning arr[i] = 0 changes that stored position.

Nonnegative entries keep their old values. The list length and order of positions stay unchanged; this does not delete negatives. Iterating indexes is important because rebinding a separate element variable would not update the original integer entry.

Does zero change? No. It is not negative.

Does an empty list cause an error? No. There are no indexes to visit.

Quiz

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

Question 1

Which assignment modifies the list?

Pick an answer to check it.

Question 2

Does zero change?

Pick an answer to check it.

Questions people ask

Does zero change?

No. It is not negative.

Does an empty list cause an error?

No. There are no indexes to visit.

Which assignment modifies the list?

arr[i] = 0.