Replace Negative Values in a List with Python

This code defines a function that replaces every negative number in a list with a replacement value, defaulting to zero, using a list comprehension.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 14 views 0 copies

Python code

8 lines
Python 3.9+
def replace_if_negative(values, replacement=0):
    return [replacement if value < 0 else value for value in values]

if __name__ == "__main__":
    numbers = [5, -3, 8, -1, 0, -7, 2]
    result = replace_if_negative(numbers)
    print(f"Original: {numbers}")
    print(f"Replaced: {result}")

Output

stdout
Original: [5, -3, 8, -1, 0, -7, 2]
Replaced: [5, 0, 8, 0, 0, 0, 2]

How it works

The list comprehension iterates over each element in the input list and applies a conditional expression: if the element is negative, it substitutes the replacement value; otherwise, it keeps the original. This approach is concise and efficient, avoiding the need for explicit loops or temporary lists. The function is pure – it does not modify the original list, making it safe for reuse.

Common mistakes

  • Forgetting that the condition checks for negative values, not non-positive (zero is not replaced)
  • Modifying the original list in place instead of returning a new list
  • Using `elif` or multiple conditions when a single conditional expression suffices

Variations

  1. Use a for loop with append for readability: `result = []; for v in numbers: result.append(0 if v < 0 else v)`
  2. Use `map` with a lambda: `list(map(lambda v: 0 if v < 0 else v, numbers))`

Real-world use cases

  • Cleaning a dataset by replacing invalid sensor readings (negative values) with a default baseline before analysis.
  • Sanitizing user input in a financial application by converting negative transaction amounts to zero for aggregation.
  • Preprocessing feature values in a machine learning pipeline to bound them to non-negative ranges.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.