Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk5 min

How to Get Absolute Value in Python Without Using abs()

Use x if x >= 0 else -x to get the absolute value of ordinary Python numbers without abs(). Learn when math.fabs(), Decimal.copy_abs() or explicit complex magnitude is the right choice, and where the conditional fails for complex values and NaN.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For an ordinary Python int or float, you can get the absolute value without calling abs() by using a conditional expression: x if x >= 0 else -x. It returns x when x is nonnegative and its negation otherwise. The pattern is sound for ordered real numbers. Complex numbers and NaN need different handling, which is covered below.

The manual implementation

The one-line form is the most compact option:

x = -7
absolute_value = x if x >= 0 else -x
print(absolute_value)  # 7

The same logic written as a full statement is easier to read in teaching code or when the branch needs more work:

if x < 0:
    absolute_value = -x
else:
    absolute_value = x

Why the pattern works

The condition picks one of two operands. A nonnegative value is kept as it is. A negative value goes through unary negation, which flips its sign and leaves a positive result. Because the operand is returned unchanged, the result keeps the input’s type: an int stays an int and a float stays a float.

Unary negation on its own is not absolute value. Multiplying by -1 or applying -x to every input would flip positive numbers too, so the test on the sign is what makes the technique work.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

One edge case is worth knowing. Negative zero (-0.0) satisfies -0.0 >= 0, so the conditional returns -0.0. The built-in abs(-0.0) returns 0.0. In arithmetic the two behave the same, but they print differently and can matter in formatting or sign-sensitive code.

Alternatives that avoid calling abs() by name

math.fabs() for floating-point code

math.fabs(x) from the math module returns the absolute value as a float, even when you pass an integer. The function is for real numbers and rejects complex input.

import math
math.fabs(-7)     # 7.0
math.fabs(-2.5)   # 2.5

Use it when a float result is acceptable and a function call is not forbidden. If your code must preserve int type, the conditional expression is the better fit.

Decimal values

The decimal module provides its own absolute-value operation. For a Decimal instance, copy_abs() returns the absolute value, and the decimal context also offers an abs operation. Decimal supports special values such as NaN and infinities, and those follow the Decimal module’s own rules, so check them against your policy before relying on a branch.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from decimal import Decimal
Decimal("-2.50").copy_abs()   # Decimal('2.50')

If your restriction covers only the built-in abs() call, the method is a legitimate alternative. If the restriction covers any absolute-value operation, a manual conditional on the Decimal value still works for ordinary finite numbers.

Complex numbers

Complex values cannot be used with < or >=. Python does not define an ordering for complex numbers, so the conditional pattern raises a TypeError instead of returning a magnitude. Comparing a complex number with zero is not a workaround either.

The mathematically meaningful quantity is the magnitude, the distance from the origin in the complex plane. You can compute it directly from the real and imaginary parts:

import math
z = 3 + 4j
magnitude = math.hypot(z.real, z.imag)   # 5.0

This is the same quantity the built-in abs() returns for complex input, so use it only if the exercise or policy allows explicit magnitude computation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Where the conditional approach fails

NaN values

NaN is not an ordinary ordered value. Every ordered comparison with NaN returns false, so x >= 0 is false and -x returns NaN as well. The branch therefore gives no meaningful answer for NaN without an explicit rule. The simplest documented policy is to return NaN unchanged, and the check for it uses the fact that NaN is the only value not equal to itself:

def manual_abs(x):
    if x != x:          # NaN check
        return x        # policy: propagate NaN
    return x if x >= 0 else -x

If your code should reject NaN instead, raise a ValueError in the same branch.

Types without an ordering

The conditional works only when the input supports >= with zero and negation. That covers int, float and Fraction. It fails for complex numbers, as described above, and for any custom numeric type that does not define these operations.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choosing an approach

Input type Expression Result type Limitation
Real int or float, no function call needed x if x >= 0 else -x Same as input Returns -0.0 for negative zero; NaN needs a separate check
Real number, float result acceptable math.fabs(x) float Rejects complex input; always returns float
Decimal x.copy_abs() Decimal Special values (NaN, infinities) follow Decimal rules
Complex number math.hypot(z.real, z.imag) float Requires explicit computation; no ordering exists for the conditional
Float that may be NaN NaN check plus conditional Same as input for numbers The policy for NaN (propagate or raise) must be chosen and documented

Common mistakes

  • Using x * -1 for every input. It turns positive values negative.
  • Treating -x as absolute value. Negation only reverses the sign.
  • Assuming x < 0 works for all Python numbers. It fails for complex values and gives false results for NaN.
  • Expecting math.fabs() to keep integers as integers. It always returns a float.
  • Calling a value “positive” when you mean its absolute value. These differ for special values and for types with no ordering, so the conditional is only a correct absolute value where the ordering applies.

Which approach to use

  • Exercise that forbids abs() with plain numbers: use the conditional expression and state that it covers real numbers.
  • Floating-point code where a call is acceptable: use math.fabs().
  • Decimal money or precision work: use copy_abs() if only the built-in call is restricted.
  • Complex input: compute the magnitude explicitly with math.hypot(), and say so in the code’s documentation.
  • Production code with no restriction: the built-in abs() is the idiomatic choice. It handles integers, floats, Decimal and complex numbers without extra branching.

The conditional expression is a teaching and restricted-environment tool. It is not a replacement for abs() in general code.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Sources and version notes

The behavior described here is documented in Python’s reference pages for the built-in functions, the expression reference (which covers comparisons and NaN), the math module and the decimal module. The conditional expression relies only on core syntax. The math.fabs() and Decimal methods have been part of the standard library for many years, but if you target an older interpreter, confirm each call against your project’s Python version.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.