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.
Python code
8 linesdef 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
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
- Use a for loop with append for readability: `result = []; for v in numbers: result.append(0 if v < 0 else v)`
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.