## abs() in Python

**The Python abs() function** return the absolute value and remove the negative sign of a number in Python.

### Python abs() Function Syntax

**number:**Integer, floating-point number, complex number.

### Python abs() Function Example

Python **abs()** Function with int in Python.

### Python3

**Output:**

#### Example 1: Get the absolute value of a number

In this example, we pass int data into the abs() function and it will return an absolute value.

### Python3

**Output:**

#### Example 2: Get the absolute value of a floating number

In this example, we pass float data into the abs() function and it will return an absolute value.

### Python3

**Output:**

#### Example 3: Get the absolute value of a complex number

In this example, we pass Python complex data into the abs() function and it will return an absolute value.

### Python3

**Output:**

#### Example 4: Time-Distance calculation using Python abs()

This equation shows the relationship between speed, distance traveled and time taken and we know speed, time and distance are never negative, for this, we will use abs() methods to calculate the exact time, distance, and speed.

Formula used:Distance = Speed * Time

Time = Distance / Speed

Speed = Distance / Time

## abc — Abstract Base Classes¶

This module provides the infrastructure for defining abstract base classes (ABCs) in Python, as outlined in **PEP 3119**; see the PEP for why this was added to Python. (See also **PEP 3141** and the numbers module regarding a type hierarchy for numbers based on ABCs.)

The collections module has some concrete classes that derive from ABCs; these can, of course, be further derived. In addition, the collections.abc submodule has some ABCs that can be used to test whether a class or instance provides a particular interface, for example, if it is hashable or if it is a mapping.

This module provides the metaclass ABCMeta for defining ABCs and a helper class ABC to alternatively define ABCs through inheritance:

A helper class that has ABCMeta as its metaclass. With this class, an abstract base class can be created by simply deriving from ABC avoiding sometimes confusing metaclass usage, for example:

Note that the type of ABC is still ABCMeta , therefore inheriting from ABC requires the usual precautions regarding metaclass usage, as multiple inheritance may lead to metaclass conflicts. One may also define an abstract base class by passing the metaclass keyword and using ABCMeta directly, for example:

New in version 3.4.

Metaclass for defining Abstract Base Classes (ABCs).

Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs as “virtual subclasses” – these and their descendants will be considered subclasses of the registering ABC by the built-in issubclass() function, but the registering ABC won’t show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even via super() ). 1

Classes created with a metaclass of ABCMeta have the following method:

Register *subclass* as a “virtual subclass” of this ABC. For example:

Changed in version 3.3: Returns the registered subclass, to allow usage as a class decorator.

Changed in version 3.4: To detect calls to register() , you can use the get_cache_token() function.

You can also override this method in an abstract base class:

(Must be defined as a class method.)

Check whether *subclass* is considered a subclass of this ABC. This means that you can customize the behavior of issubclass further without the need to call register() on every class you want to consider a subclass of the ABC. (This class method is called from the __subclasscheck__() method of the ABC.)

This method should return True , False or NotImplemented . If it returns True , the *subclass* is considered a subclass of this ABC. If it returns False , the *subclass* is not considered a subclass of this ABC, even if it would normally be one. If it returns NotImplemented , the subclass check is continued with the usual mechanism.

For a demonstration of these concepts, look at this example ABC definition:

The ABC MyIterable defines the standard iterable method, __iter__() , as an abstract method. The implementation given here can still be called from subclasses. The get_iterator() method is also part of the MyIterable abstract base class, but it does not have to be overridden in non-abstract derived classes.

The __subclasshook__() class method defined here says that any class that has an __iter__() method in its __dict__ (or in that of one of its base classes, accessed via the __mro__ list) is considered a MyIterable too.

Finally, the last line makes Foo a virtual subclass of MyIterable , even though it does not define an __iter__() method (it uses the old-style iterable protocol, defined in terms of __len__() and __getitem__() ). Note that this will not make get_iterator available as a method of Foo , so it is provided separately.

The abc module also provides the following decorator:

A decorator indicating abstract methods.

Using this decorator requires that the class’s metaclass is ABCMeta or is derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods and properties are overridden. The abstract methods can be called using any of the normal ‘super’ call mechanisms. abstractmethod() may be used to declare abstract methods for properties and descriptors.

Dynamically adding abstract methods to a class, or attempting to modify the abstraction status of a method or class once it is created, are only supported using the update_abstractmethods() function. The abstractmethod() only affects subclasses derived using regular inheritance; “virtual subclasses” registered with the ABC’s register() method are not affected.

When abstractmethod() is applied in combination with other method descriptors, it should be applied as the innermost decorator, as shown in the following usage examples:

In order to correctly interoperate with the abstract base class machinery, the descriptor must identify itself as abstract using __isabstractmethod__ . In general, this attribute should be True if any of the methods used to compose the descriptor are abstract. For example, Python’s built-in property does the equivalent of:

Unlike Java abstract methods, these abstract methods may have an implementation. This implementation can be called via the super() mechanism from the class that overrides it. This could be useful as an end-point for a super-call in a framework that uses cooperative multiple-inheritance.

The abc module also supports the following legacy decorators:

New in version 3.2.

Deprecated since version 3.3: It is now possible to use classmethod with abstractmethod() , making this decorator redundant.

A subclass of the built-in classmethod() , indicating an abstract classmethod. Otherwise it is similar to abstractmethod() .

This special case is deprecated, as the classmethod() decorator is now correctly identified as abstract when applied to an abstract method:

New in version 3.2.

Deprecated since version 3.3: It is now possible to use staticmethod with abstractmethod() , making this decorator redundant.

A subclass of the built-in staticmethod() , indicating an abstract staticmethod. Otherwise it is similar to abstractmethod() .

This special case is deprecated, as the staticmethod() decorator is now correctly identified as abstract when applied to an abstract method:

Deprecated since version 3.3: It is now possible to use property , property.getter() , property.setter() and property.deleter() with abstractmethod() , making this decorator redundant.

A subclass of the built-in property() , indicating an abstract property.

This special case is deprecated, as the property() decorator is now correctly identified as abstract when applied to an abstract method:

The above example defines a read-only property; you can also define a read-write abstract property by appropriately marking one or more of the underlying methods as abstract:

If only some components are abstract, only those components need to be updated to create a concrete property in a subclass:

The abc module also provides the following functions:

Returns the current abstract base class cache token.

The token is an opaque object (that supports equality testing) identifying the current version of the abstract base class cache for virtual subclasses. The token changes with every call to ABCMeta.register() on any ABC.

New in version 3.4.

A function to recalculate an abstract class’s abstraction status. This function should be called if a class’s abstract methods have been implemented or changed after it was created. Usually, this function should be called from within a class decorator.

Returns *cls*, to allow usage as a class decorator.

If *cls* is not an instance of ABCMeta , does nothing.

This function assumes that *cls*’s superclasses are already updated. It does not update any subclasses.

New in version 3.10.

C++ programmers should note that Python’s virtual base class concept is not the same as C++’s.

## How to Find an Absolute Value in Python

Absolute values are commonly used in mathematics, physics, and engineering. Although the school definition of an absolute value might seem straightforward, you can actually look at the concept from many different angles. If you intend to work with absolute values in Python, then you’ve come to the right place.

**In this tutorial, you’ll learn how to:**

- Implement the
**absolute value**function from scratch - Use the
**built-in abs() function**in Python - Calculate the absolute values of
**numbers** - Call abs() on
**NumPy arrays**and**pandas series** **Customize**the**behavior**of abs() on objects

Don’t worry if your mathematical knowledge of the absolute value function is a little rusty. You’ll begin by refreshing your memory before diving deeper into Python code. That said, feel free to skip the next section and jump right into the nitty-gritty details that follow.

**Sample Code:** Click here to download the sample code that you’ll use to find absolute values in Python.

### Defining the Absolute Value

The absolute value lets you determine the **size** or **magnitude** of an object, such as a number or a vector, regardless of its direction. Real numbers can have one of two directions when you ignore zero: they can be either positive or negative. On the other hand, complex numbers and vectors can have many more directions.

**Note:** When you take the absolute value of a number, you lose information about its sign or, more generally, its direction.

Consider a temperature measurement as an example. If the thermometer reads -12°C, then you can say it’s twelve degrees Celsius below freezing. Notice how you decomposed the temperature in the last sentence into a magnitude, twelve, and a sign. The phrase *below freezing* means the same as below zero degrees Celsius. The temperature’s size or absolute value is identical to the absolute value of the much warmer +12°C.

Using mathematical notation, you can define the absolute value of as a piecewise function, which behaves differently depending on the range of input values. A common symbol for absolute value consists of two vertical lines:

Absolute Value Defined as a Piecewise Function

This function returns values greater than or equal to zero without alteration. On the other hand, values smaller than zero have their sign flipped from a minus to a plus. Algebraically, this is equivalent to taking the square root of a number squared:

Absolute Value Defined Algebraically

When you square a real number, you always get a positive result, even if the number that you started with was negative. For example, the square of -12 and the square of 12 have the same value, equal to 144. Later, when you compute the square root of 144, you’ll only get 12 without the minus sign.

Geometrically, you can think of an absolute value as the **distance** from the origin, which is zero on a number line in the case of the temperature reading from before:

Absolute Value on a Number Line

To calculate this distance, you can subtract the origin from the temperature reading (-12°C — 0°C = -12°C) or the other way around (0°C — (-12°C) = +12°C), and then drop the sign of the result. Subtracting zero doesn’t make much difference here, but the reference point may sometimes be shifted. That’s the case for vectors bound to a fixed point in space, which becomes their origin.

Vectors, just like numbers, convey information about the **direction** and the **magnitude** of a physical quantity, but in more than one dimension. For example, you can express the velocity of a falling snowflake as a three-dimensional vector:

This vector indicates the snowflake’s current position relative to the origin of the coordinate system. It also shows the snowflake’s direction and pace of motion through the space. The longer the vector, the greater the magnitude of the snowflake’s speed. As long as the coordinates of the vector’s initial and terminal points are expressed in meters, calculating its length will get you the snowflake’s speed measured in meters per unit of time.

**Note:** There are two ways to look at a vector. A *bound* vector is an ordered pair of fixed points in space, whereas a *free* vector only tells you about the displacement of the coordinates from point A to point B without revealing their absolute locations. Consider the following code snippet as an example:

A bound vector wraps both points, providing quite a bit of information. In contrast, a free vector only represents the shift from A to B. You can calculate a free vector by subtracting the initial point, A, from the terminal one, B. One way to do so is by iterating over the consecutive pairs of coordinates with a list comprehension.

A free vector is essentially a bound vector translated to the origin of the coordinate system, so it begins at zero.

The **length** of a vector, also known as its magnitude, is the distance between its initial and terminal points, and , which you can calculate using the Euclidean norm:

The Length of a Bound Vector as a Euclidean Norm

This formula calculates the length of the -dimensional vector , by summing the squares of the differences between the coordinates of points and in each dimension indexed by . For a free vector, the initial point, , becomes the origin of the coordinate system—or zero—which simplifies the formula, as you only need to square the coordinates of your vector.

Recall the algebraic definition of an absolute value. For numbers, it was the square root of a number squared. Now, when you add more dimensions to the equation, you end up with the formula for the Euclidean norm, shown above. So, the absolute value of a vector is equivalent to its length!

All right. Now that you know when absolute values might be useful, it’s time to implement them in Python!

### Implementing the Absolute Value Function in Python

To implement the absolute value function in Python, you can take one of the earlier mathematical definitions and translate it into code. For instance, the piecewise function may look like this:

You use a conditional statement to check whether the given number denoted with the letter x is greater than or equal to zero. If so, then you return the same number. Otherwise, you flip the number’s sign. Because there are only two possible outcomes here, you can rewrite the above function using a conditional expression that comfortably fits on a single line:

It’s exactly the same behavior as before, only implemented in a slightly more compact way. Conditional expressions are useful when you don’t have a lot of logic that goes into the two alternative branches in your code.

**Note:** Alternatively, you can write this even more concisely by relying on Python’s built-in max() function, which returns the largest argument:

If the number is negative, then this function will return its positive value. Otherwise, it’ll return itself.

The algebraic definition of an absolute value is also pretty straightforward to implement in Python:

First, you import the square root function from the math module and then call it on the given number raised to the power of two. The power function is built right into Python, so you don’t have to import it. Alternatively, you can avoid the import statement altogether by leveraging Python’s exponentiation operator ( ** ), which can simulate the square root function:

This is sort of a mathematical trick because using a fractional exponent is equivalent to computing the th root of a number. In this case, you take a squared number to the power of one-half (0.5) or one over two (½), which is the same as calculating the square root. Note that both Python implementations based on the algebraic definition suffer from a slight deficiency:

You always end up with a floating-point number, even if you started with an integer. So, if you’d like to preserve the original data type of a number, then you might prefer the piecewise-based implementation instead.

As long as you stay within integers and floating-point numbers, you can also write a somewhat silly implementation of the absolute value function by leveraging the textual representation of numbers in Python:

You convert the function’s argument, x , to a Python string using the built-in str() function. This lets you replace the leading minus sign, if there is one, with an empty string. Then, you convert the result to a floating-point number with float() .

Implementing the absolute value function from scratch in Python is a worthwhile learning exercise. However, in real-life applications, you should take advantage of the built-in abs() function that comes with Python. You’ll find out why in the next section.

### Using the Built-in abs() Function With Numbers

The last function that you implemented above was probably the least efficient one because of the data conversions and the string operations, which are usually slower than direct number manipulation. But in truth, all of your hand-made implementations of an absolute value pale in comparison to the abs() function that’s built into the language. That’s because abs() is compiled to blazing-fast machine code, while your pure-Python code isn’t.

You should always prefer abs() over your custom functions. It runs much more quickly, an advantage that can really add up when you have a lot of data to process. Additionally, it’s much more versatile, as you’re about to find out.

#### Integers and Floating-Point Numbers

The abs() function is one of the built-in functions that are part of the Python language. That means you can start using it right away without importing:

As you can see, abs() preserves the original data type. In the first case, you passed an integer literal and got an integer result. When called with a floating-point number, the function returned a Python float . But these two data types aren’t the only ones that you can call abs() on. The third numeric type that abs() knows how to handle is Python’s complex data type, which represents complex numbers.

#### Complex Numbers

You can think of a complex number as a pair consisting of two floating-point values, commonly known as the **real part** and the **imaginary part**. One way to define a complex number in Python is by calling the built-in complex() function:

It accepts two arguments. The first one represents the real part, while the second one represents the imaginary part. At any point, you can access the complex number’s .real and .imag attributes to get those parts back:

Both of them are read-only and are always expressed as floating-point values. Also, the absolute value of a complex number returned by abs() happens to be a floating-point number:

This might surprise you until you find out that complex numbers have a visual representation that resembles two-dimensional vectors fixed at the coordinate system’s origin:

You already know the formula to calculate the length of such a vector, which in this case agrees with the number returned by abs() . Note that the absolute value of a complex number is more commonly referred to as the **magnitude**, **modulus**, or **radius** of a complex number.

While integers, floating-point numbers, and complex numbers are the only numeric types supported natively by Python, you’ll find two additional numeric types in its standard library. They, too, can interoperate with the abs() function.

#### Fractions and Decimals

The abs() function in Python accepts all numeric data types available, including the lesser-known fractions and decimals. For instance, you can get the absolute value of one-third or minus three-quarters defined as Fraction instances:

In both cases, you get another Fraction object back, but it’s unsigned. That can be convenient if you plan to continue your computations on fractions, which offer higher precision than floating-point numbers.

If you’re working in finance, then you’ll probably want to use Decimal objects to help mitigate the floating-point representation error. Luckily, you can take the absolute value of these objects:

Again, the abs() function conveniently returns the same data type as the one that you supplied, but it gives you an appropriate positive value.

Wow, abs() can deal with an impressive variety of numeric data types! But it turns out that abs() is even more clever than that. You can even call it on some objects delivered by third-party libraries, as you’ll try out in the next section.

### Calling abs() on Other Python Objects

Say you want to compute the absolute values of average daily temperature readings over some period. Unfortunately, as soon as you try calling abs() on a Python list with those numbers, you get an error:

That’s because abs() doesn’t know how to process a list of numbers. To work around this, you could use a list comprehension or call Python’s map() function, like so:

Both implementations do the job but require an additional step, which may not always be desirable. If you want to cut that extra step, then you may look into external libraries that change the behavior of abs() for your convenience. That’s what you’ll explore below.

#### NumPy Arrays and pandas Series

One of the most popular libraries for extending Python with high-performance arrays and matrices is NumPy. Its -dimensional array data structure, ndarray , is the cornerstone of **numerical computing** in Python, so many other libraries use it as a foundation.

Once you convert a regular Python list to a NumPy array with np.array() , you’ll be able to call some of the built-in functions, including abs() , on the result:

In response to calling abs() on a NumPy array, you get another array with the absolute values of the original elements. It’s as if you iterated over the list of temperature readings yourself and applied the abs() function on each element individually, just as you did with a list comprehension before.

You can convert a NumPy array back to a Python list if you find that more suitable:

However, note that NumPy arrays share most of the Python list interface. For example, they support indexing and slicing, and their methods are similar to those of plain lists, so most people usually just stick to using NumPy arrays without ever looking back at lists.

pandas is another third-party library widely used in **data analysis** thanks to its Series and DataFrame objects. A series is a sequence of observations or a column, whereas a DataFrame is like a table or a collection of columns. You can call abs() on both of them.

Suppose you have a Python dictionary that maps a city name to its lowest average temperatures observed monthly over the course of a year:

Each city has twelve temperature readings, spanning from January to December. Now, you can turn that dictionary into a pandas DataFrame object so that you can draw some interesting insights going forward:

Instead of using the default zero-based index, your DataFrame is indexed by abbreviated month names, which you obtained with the help of the calendar module. Each column in the DataFrame has a sequence of temperatures from the original dictionary, represented as a Series object:

By using the square bracket ( [] ) syntax and a city name like Rovaniemi, you can extract a single Series object from the DataFrame and narrow down the amount of information displayed.

pandas, just like NumPy, lets you call many of Python’s built-in functions on its objects, including its DataFrame and Series objects. Specifically, you can call abs() to calculate more than one absolute value in one go:

Calling abs() on the entire DataFrame applies the function to each element in every column. You can also call abs() on the individual column.

How did NumPy and pandas change the behavior of Python’s built-in abs() function without modifying its underlying code? Well, it was possible because the function was designed with such extensions in mind. If you’re looking for an advanced use of abs() , then read on to make your own data type that’ll play nicely with that function.

#### Your Very Own Data Types

Depending on the data type, Python will handle the computation of absolute values differently.

When you call abs() on an integer, it’ll use a custom code snippet that resembles your piecewise function. However, that function will be implemented in the C programming language for efficiency. If you pass a floating-point number, then Python will delegate that call to C’s fabs() function. In the case of a complex number, it’ll call the hypot() function instead.

What about container objects like DataFrames, series, and arrays?

Understandably, when you define a new data type in Python, it won’t work with the abs() function because its default behavior is unknown. However, you can optionally customize the behavior of abs() against the instances of your class by implementing the special .__abs__() method using pure Python. There’s a finite set of predefined special methods in Python that let you override how certain functions and operators should work.

Consider the following class representing a free -dimensional vector in the Euclidean space:

This class accepts one or more coordinate values, describing the displacement in each dimension from the origin of the coordinate system. Your special .__abs__() method calculates the distance from the origin, according to the **Euclidean norm** definition that you learned at the beginning of this tutorial.

To test your new class, you can create a three-dimensional **velocity vector** of a falling snowflake, for example, which might look like this:

Notice how calling abs() on your Vector class instance returns the correct absolute value, equal to about 1.78. The speed units will be expressed in meters per second as long as the snowflake’s displacement was measured in meters at two distinct time instants one second apart. In other words, it would take one second for the snowflake to travel from point A to point B.

Using the mentioned formula forces you to define the origin point. However, because your Vector class represents a free vector rather than a bound one, you can simplify your code by calculating the multidimensional hypotenuse using Python’s math.hypot() function:

You get the same result with fewer lines of code. Note that hypot() is a variadic function accepting a variable number of arguments, so you must use the star operator ( * ) to unpack your tuple of coordinates into those arguments.

Awesome! You can now implement your own library, and Python’s built-in abs() function will know how to work with it. You’ll get functionality similar to working with NumPy or pandas!

### Conclusion

Implementing formulas for an absolute value in Python is a breeze. However, Python already comes with the versatile abs() function, which lets you calculate the absolute value of various types of numbers, including integers, floating-point numbers, complex numbers, and more. You can also use abs() on instances of custom classes and third-party library objects.

**In this tutorial, you learned how to:**

- Implement the
**absolute value**function from scratch - Use the
**built-in abs() function**in Python - Calculate the absolute values of
**numbers** - Call abs() on
**NumPy arrays**and**pandas series** **Customize**the**behavior**of abs() on objects

With this knowledge, you’re equipped with an efficient tool to calculate absolute values in Python.

**Sample Code:** Click here to download the sample code that you’ll use to find absolute values in Python.

## Функция abs() в Python

В этой статье мы представим функцию Python abs() с различными модулями, такими как NumPy и Pandas.

Python имеет огромное количество встроенных функций для выполнения математических и статистических операций. Одной из таких функций является функция abs().

Функция abs() function возвращает абсолютную величину или значение входных данных, переданных ей в качестве аргумента. Он возвращает фактическое значение ввода без учета знака.

Она принимает только один аргумент, который должен быть числом, и возвращает абсолютную величину числа.