Kodeclik Logo

Our Programs

Learn More

Schedule

Kodeclik Blog

How to negate a number in Python

There will come a time when you will need to negate a number in Python. For instance in normalization, error correction, or data pre-processing you might need to negate a number so that all numbers are within a standard range. In doing accounting with a spreadsheet, you might need to represent debits with negative numbers. In physics calculations, you will need to represent opposing forces as negative values.

Here are four methods to make a number negative in Python, with explanations for each code snippet:

How to make something negative in Python

Method 1: Using the Negation Operator

def negate_number(num):
    return -num

# Example usage
positive_num = 42
negative_num = negate_number(positive_num)
print(f"Original number: {positive_num}")
print(f"Negated number: {negative_num}")

This method uses the unary minus operator (-) to negate a number. The negate_number function takes a single argument num and returns its negation. When applied to a positive number, it returns its negative counterpart. The example demonstrates how to use this function with a positive number and prints both the original and negated values.

The main disadvantage of this method is that when you supply a negative number, it will flip it to positive! (But read on to see other solutions that don’t have this issue!)

Method 2: Multiplying by -1

def make_negative(num):
    return num * -1

# Example usage
original_num = 123
negated_num = make_negative(original_num)
print(f"Original number: {original_num}")
print(f"Negated number: {negated_num}")

This method achieves negation by multiplying the input number by -1. The make_negative function takes a number num as input and returns the result of multiplying it by -1. This approach is mathematically equivalent to using the negation operator but makes the operation more explicit. The example shows how to use this function with a positive number and displays both the original and negated values.

This method has the same disadvantage as the previous method, i.e., when you supply a negative number, it will change it back to positive.

Method 3: Using the abs() Function

This method overcomes the deficiencies of the above two methods.

def force_negative(num):
    return -abs(num)

# Example usage
numbers = [10, -5, 0, 42, -17]
negated_numbers = [force_negative(num) for num in numbers]
print("Original numbers:", numbers)
print("Forced negative numbers:", negated_numbers)

This method ensures that the output is always negative, regardless of the input's sign. The force_negative function uses the abs() function to get the absolute value of the input, then negates it. This approach is useful when you want to guarantee a negative result, even if the input is already negative or zero. The example demonstrates how to apply this function to a list of numbers with mixed signs using a list comprehension, showing the versatility of this method.

Method 4: Using a Lambda Function

Finally, let us use a lambda function and try to retain the property that negative inputs continue to stay negative:

import random

# Generate a list of random numbers
numbers = [random.randint(-50, 50) for _ in range(10)]

# Create a lambda function to negate numbers
negate = lambda x: -x if x > 0 else x

# Apply the negation to all positive numbers in the list
negated_numbers = list(map(negate, numbers))

print("Original numbers:", numbers)
print("Negated numbers:", negated_numbers)

This method showcases the use of a lambda function for negation, which is particularly useful in functional programming contexts. The code first generates a list of random numbers between -50 and 50. The lambda function negate is defined to return the negation of a number if it's positive, or the number itself if it's negative or zero. This function is then applied to each element in the numbers list using the map() function, effectively negating all positive numbers while leaving non-positive numbers unchanged. This approach demonstrates how to selectively apply negation based on a condition and how to use lambda functions with built-in higher-order functions like map().

Note that we have avoided using conditional statements as much as we could (save for the lambda definition in the last method). There is just no one right way to solve problems in Python! So pick your favorite approach and learn the pros and cons of that approach!

If you liked this blogpost, checkout our blogpost on how to multiply numbers in Python and how to find the average of a list!

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.