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.
1# Take array2n = int(input("Enter array size: "))3arr = []4for i in range(n):5 arr.append(int(input(f"Element {i+1}: ")))67# Replace negatives8for i in range(len(arr)):9 if arr[i] < 0:10 arr[i] = 01112print(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
Visit valid indexes of arr.
- 2
Test whether arr[i] is negative.
- 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.
๐Related Content
- ๐
Phase 4 - Learn Concepts
Review Phase 4 concepts and explanations
- ๐
Phase 4 - Quiz
Test your Phase 4 understanding with quiz questions
- ๐ป
Phase 4 - All Practice Problems
Explore all practice problems for Phase 4
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum