Replace Negatives with 0

Replace all negative elements with 0.

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]

What's going on

Modify array in-place.

Key Concepts:

Check each element
Replace if negative
In-place modification