# Python abs(): The Absolute Value Built-in Function

###### Finding the absolute value has applications in nearly every field where numbers are involved. Python celebrates this universal applicability by offering a powerful built-in function for calculating the absolute value of a number. The Python abs() function is part of the standard built-in functions and provides a utility to calculate an absolute value. This function can be used to convert static values to their absolute value as well as dynamic values. In this article, I’ll cover the basic syntax used for Python’s absolute value function, how to use it, and some common use cases.

TL;DR – Python’s built-in `abs()` function can be used without any imports to calculate the absolute value of any number as such:

```# Calculate the absolute value of a static number
>>> abs(-42)
42

# Calculate the absolute value of some crazy dynamic value
>>> abs((lambda x, y={0: -42}: x * y).__defaults__)
42```

## Introduction

Absolute value is the measure of a number’s distance to zero. Negative five is five-unit measures from zero therefore its absolute value is five—not negative five. This mathematical notation is simple but does come with some more complex implications. Don’t worry—you don’t need to know the finer points of integrals or differentiable functions to appreciate—and apply—Python’s absolute value function.

## The Basics

Python uses the built-in abs() function to calculate absolute value. The official Python definition is as follows:

Return the absolute value of a number. The argument may be an integer, a floating-point number, or an object implementing __abs__(). If the argument is a complex number, its magnitude is returned.

It can be applied as follows to integers, floating-point values, and even complex numbers. To get a basic feel for the abs() function let’s do some basic calculations and comparisons.

```# Getting the value of positives
>>> abs(5)
5

# Getting the value of negatives
>>> abs(-5)
5

# Comparing integers
>> abs(-42) == abs(42)
True

# Comparing floats
>>> abs(-42.0) == abs(42.0)
True

# Compare integers vs. floats
>>> abs(-42.0) == abs(42)
True

# Compare complex numbers
>>> abs(-1j) == abs(1j)
True

# Whatever this is
>>> abs(-3j * 5 + 4)
15.524174696260024

# Functions
>>> abs(```

Python’s absolute value function only takes a single argument—the value of which one wishes to calculate the absolute value. This value can be a `float`, `integer`, complex number, or even a dynamic value from a function.

## Stretching Our Legs

Python’s absolute value function, like the other built-ins, can be used for damn near anything one can imagine. I use it often when making calculations based on stock prices. I know others that use is often for computing values related to 3D graphics. It is versatile, simple, and syntactically seamless. Here are a few examples of using the abs function in more dynamic settings:

```import random

# Get a list of 10 random integers in range -10 to 10
r_list = [random.choice(list(range(-10, 10, 1))) for x in range(10)]
>>> [9, -10, 2, -3, 0, 9, -6, -9, -2, -9]

# Sort the list based on absolute value
r_list = sorted(r_list, key=lambda x: abs(x))
>>> [0, 2, -2, -3, -6, 9, 9, -9, -9, -10]

# Do some square rooting
import math

# Try to calculate the square of negative
s_list = [math.sqrt(x) for x in r_list]
>>> ValueError: math domain error

# Convert to absolute and succeed
s_list = [round(math.sqrt(abs(x)), 2) for x in r_list]
[0.0, 1.41, 1.41, 1.73, 2.45, 3.0, 3.0, 3.0, 3.0, 3.16]
```

## Objects & __abs__()

Python objects implement a number of standard operators, methods, and attributes. Python represents all data as an object or relation between objects. The attributes and characteristics of these entities and relationships are defined by the Python data model. There is a lot of complexity thereof which I’ll not dare to touch on here.

Amidst this complexity is the `__abs__()` feature to define a model’s absolute representation. This is used to implement Python’s `abs()` function using any custom approach that may be needed. For example, Python’s built-in int class is an object that implements an `__abs__()` method to define how it returns and absolute value. Finding that in the source is damn-near impossible so let’s consider a custom example.

```# Create a custom class with custom abs implementation
class CustomInt:
"""Custom class to mimic an integer value"""
def __init__(self, val: int):
"""Initializes the object with value"""
self.val = val

def __abs__(self):
"""Defines how to calculate absolute values"""
return int((self.val ** 2) ** 0.5)

def __str__(self):
"""Defines what gets printed to the console"""
return str(self.val)

# Create a custom int and display value
c_int = CustomInt(-5)
>>> -5

# Get the absolute value
abs(c_int)
>>> 5

# Compare to another absolute value
abs(c_int) == abs(-5)
>>> True```

This looks great! Our `CustomInt` object implements an absolute value function as one would expect if asked to manually calculate it. Another possible option would have simply been to return a value of `abs(self.val)` leveraging Python’s built-in abs function. That wouldn’t let us showcase how meddling in the way absolute values are calculated can cause an issue:

```class CusdumbInt:
"""Custom class to mimic an integer value"""
def __init__(self, val: int):
"""Initializes the object with value"""
self.val = val

def __abs__(self):
"""Calculates Absolute value erroneously"""
return 15

def __str__(self):
"""Defines what gets printed to the console"""
return str(self.val)

# Create an instance of our new object
# initialized with a value of -5
c_int = CusdumbInt(-5)
>>> -5

# Get the absolute value of our custom
# object using the built-in abs function.
abs(c_int)
>>> 15

# yikes```

By altering the definition of our `CusdumbInt` class’ `__abs__()` method we’ve affected how the `abs()` function treats our new `c_int` instance. The `abs` function instructs Python to use the `__abs__()` definition when determining our object’s absolute value. I don’t know how anyone would accidentally run into this issue but it is a possibility.

## Final Thoughts

Python’s `abs()` function provides convenient built-in ease for calculating the distance from zero for integers, floats, and even complex numbers. We’ve seen that it can be used both statically and dynamically and that the `__abs__` method of Python’s data model could toss a monkey wrench (snake wrench?) into the mix.

I find myself using this built-in quite often. When I first started learning Python I wasn’t aware and relied on the math library to provide that functionality. Little did I know, I could have been saving that one extra line of an import statement all that time! Python’s built-in functions are one of the many reasons I regard it as deserving of its inclusion among the most popular programming languages available today.

Seasoned engineer with a decade of specializing in Python and backend services for scalable applications, leveraging reusable patterns, OOP, and TDD. Strong background in Full-Stack development, design, and digital marketing. Talk to me about deep reinforcement learning, trading algorithms, web scraping, and meditation.