Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Unary Plus and Minus Operators

Learn how Python's unary plus and minus operators work, how to negate values, check signs, and handle edge cases like zero and negative zero.

~5 min readPython
#unary operators#sign manipulation#python syntax#numeric operations
Diagram showing unary plus and minus operators applied to a number line with positive and negative values.

Python's unary plus and minus operators let you control the sign of a numeric value directly in an expression. -x negates x, while +x returns x unchanged. They are useful when normalizing data, implementing sign-based logic, or working with custom numeric types.

What Unary Plus and Minus Do in Python

Unary operators act on a single operand. In Python, the + and - symbols serve dual roles: binary addition/subtraction and unary sign indication. When placed before a value, they apply the following rules:

  • +x returns x without changing its value or sign.
  • -x returns the arithmetic negation of x.

These operators work on built-in numeric types and on any object that implements the corresponding dunder methods. For built-in types like int, float, and complex, the behavior is straightforward:

python
x = 5 print(+x) # 5 print(-x) # -5 y = -3.14 print(+y) # -3.14 print(-y) # 3.14

The unary minus does not simply flip a bit; it performs a true mathematical negation. For integers, this is exact. For floats, the sign bit changes, but the magnitude remains the same. For complex numbers, both the real and imaginary parts are negated.

Using Unary Minus to Negate a Value

The most common use of unary minus is to invert the sign of a variable or expression. This is particularly useful when you need to reverse a value conditionally or when you want to apply a negative offset without mutating the original variable.

python
def reverse_sign(value): return -value current = 10 reversed_value = reverse_sign(current) print(reversed_value) # -10 print(current) # 10 (unchanged)

Unary minus also works in larger expressions, where it binds tightly to the operand. For instance, -x * y is parsed as (-x) * y, not as -(x * y).

python
x = 4 y = 3 print(-x * y) # -12; parsed as (-x) * y print(-(x * y)) # -12

For built-in numbers, the numeric result is the same in this case, but the parse distinction matters when the operand is a function call or attribute access. For example, -obj.value negates the value of obj.value, not the entire object.

Using Unary Plus to Preserve Sign

Unary plus is often ignored because it appears to do nothing. For built-in numeric values, that is exactly right: +x returns x unchanged. It is not needed to parse signed input, because int() already preserves the sign in a string:

python
def parse_signed_number(text): value = int(text) # int() already keeps the sign return value print(parse_signed_number("-42")) # -42 print(parse_signed_number("42")) # 42

Writing +int(text) would produce the same result; for built-in int, the unary plus is a no-op. The operator still matters for custom objects, because it triggers __pos__. That method can return a copy, a normalized version of the object, or any other object the class considers appropriate.

Checking Whether a Number Is Positive or Negative

While unary operators change sign, determining the sign of a number typically uses comparison operators. The standard pattern is:

python
if x > 0: print("positive") elif x < 0: print("negative") else: print("zero")

This is clear and works for real-valued numeric types such as int and float. For floats, be aware of -0.0. In Python, -0.0 is equal to 0.0 under ==, but its sign bit is set. If you need to distinguish between positive and negative zero, use math.copysign or check the sign bit directly:

python
import math value = -0.0 print(value == 0.0) # True print(math.copysign(1.0, value)) # -1.0

For complex numbers, there is no total ordering, so comparisons like z > 0 raise TypeError. You must check the real and imaginary parts separately if sign matters.

How Unary Operators Work on Custom Objects

Python allows any class to define unary operators by implementing __neg__, __pos__, and __abs__. This is useful for creating objects that behave like numbers, such as vectors or monetary amounts.

python
class Vector: def __init__(self, x, y): self.x = x self.y = y def __neg__(self): return Vector(-self.x, -self.y) def __pos__(self): return Vector(self.x, self.y) v = Vector(1, -2) neg_v = -v pos_v = +v print(neg_v.x, neg_v.y) # -1 2 print(pos_v.x, pos_v.y) # 1 -2

When you define __neg__, you should return a new instance rather than mutating the original. This matches the immutable behavior of built-in numerics. If you don't implement these methods, using - or + on your object raises TypeError.

Common Mistakes With Sign and Zero

A frequent mistake is assuming that -0 produces a different value than 0. For integers, -0 is just 0 because integers have no signed representation. For floats, -0.0 is a distinct value in terms of its sign bit, but it compares equal to 0.0. This can cause subtle bugs in code that relies on math.copysign or serialization.

Another pitfall is applying unary minus to a variable that is already negative, expecting it to become positive. That part is correct: -x is positive when x is negative. Nested unary operators, however, can be confusing. -(-x) is equal to x, not to -x:

python
x = -5 print(-x) # 5 print(-(-x)) # -5, because -(-x) is x

Performance and Readability Considerations

For built-in numeric types, these operations are cheap. Still, the main reason to prefer -x over x * -1 or 0 - x is readability: the unary form clearly expresses sign inversion and avoids an extra constant. For custom objects, the cost depends on what __neg__ and __pos__ do. If they create a new object, that allocation is the dominant cost.

When working with data streams that include both positive and negative values, unary minus can be used to normalize a sign without branching:

python
normalized = -abs(raw_value) # always non-positive

This pattern is common in signal processing and financial calculations where you need a consistent direction. It is more readable than an if-else block and avoids mutation.

Edge Cases With Non-Numeric Types

Unary operators are not limited to numbers. - on a list raises TypeError, but on a bool it works because bool is a subclass of int. -True returns -1, and -False returns 0. This can be surprising if you forget that booleans are integers in Python.

Also, + on a str raises TypeError. Only types that implement __pos__ support it. For custom classes, you can define __pos__ to return a normalized copy or to apply a transformation like rounding.

When you implement __neg__ on a custom class, consider whether the result should be the same type. If not, document it clearly. Returning a different type can break chained operations and lead to runtime errors.

Practical Example: Sign-Based Filtering

A common real-world task is filtering a list of numbers to keep only positive or negative values. Unary operators are not directly used in the filter, but sign handling is essential. Here is a concise implementation:

python
def partition_by_sign(numbers): positive = [n for n in numbers if n > 0] negative = [n for n in numbers if n < 0] zeros = [n for n in numbers if n == 0] return positive, negative, zeros data = [1, -2, 0, 3.5, -0.0, 4] pos, neg, zero = partition_by_sign(data) print(pos) # [1, 3.5, 4] print(neg) # [-2] print(zero) # [0, -0.0] because -0.0 == 0

Note that -0.0 is included in the zero list because it compares equal to 0. If you need to treat -0.0 as negative, you must check the sign bit explicitly. This edge case is why sign handling deserves careful attention in numeric code.

Summary of Operator Precedence

Unary plus and minus have higher precedence than binary operators like *, /, and +. This means -x ** 2 is parsed as -(x ** 2) because exponentiation has higher precedence than unary minus. In contrast, (-x) ** 2 squares the negated value. This distinction is critical in mathematical expressions.

python
x = 3 print(-x ** 2) # -9 print((-x) ** 2) # 9

If you are unsure about precedence, use parentheses. They cost nothing and make the intent explicit. This is especially important when mixing unary operators with exponentiation or bitwise shifts.

Final Code Example: Custom Numeric Class

To tie together the concepts, here is a small class that implements __neg__ and __pos__ to handle a signed measurement with a unit:

python
class Measurement: def __init__(self, value, unit): self.value = value self.unit = unit def __neg__(self): return Measurement(-self.value, self.unit) def __pos__(self): return Measurement(self.value, self.unit) def __repr__(self): return f"{self.value} {self.unit}" m = Measurement(10, "kg") print(-m) # -10 kg print(+m) # 10 kg

This pattern is useful for domain-specific types where sign matters and you want to avoid manual negation in every consumer. By defining unary operators, you make the class behave like a built-in numeric type, reducing boilerplate and improving maintainability.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.