You can do it like this:

A = [2, 7, 5, 9, 3, 1, 2]

temp = sorted(A)
min_diff = min([abs(i - j) for i, j in zip(temp [:-1], temp [1:])])

print(min_diff)  # -> 0

Sorting makes sure that the element pair (i, j) which produce the overall smallest difference would be a pair of consecutive elements. That makes the number of checks you have to perform much less than the brute force approach of all possible combinations.


Something a bit more clever that short-circuits:

A = [2, 7, 5, 9, 3, 1, 2]


def find_min_diff(my_list):
    if len(set(my_list)) != len(my_list):  # See note 1
        return 0
    else:
        temp = sorted(my_list)
        my_min = float('inf')
        for i, j in zip(temp [:-1], temp [1:]):
            diff = abs(i - j)
            if diff < my_min:
                my_min = diff
        return my_min

print(find_min_diff(A))  # -> 0

Notes:

1: Converting to set removes the duplicates so if the corresponding set has less elements than the original list it means that there is at least one duplicate value. But that necessarily means that the min absolute difference is 0 and we do not have to look any further.

I would be willing to bet that this is the fastest approach for all lists that would return 0.

Answer from Ma0 on Stack Overflow
Top answer
1 of 5
6

You can do it like this:

A = [2, 7, 5, 9, 3, 1, 2]

temp = sorted(A)
min_diff = min([abs(i - j) for i, j in zip(temp [:-1], temp [1:])])

print(min_diff)  # -> 0

Sorting makes sure that the element pair (i, j) which produce the overall smallest difference would be a pair of consecutive elements. That makes the number of checks you have to perform much less than the brute force approach of all possible combinations.


Something a bit more clever that short-circuits:

A = [2, 7, 5, 9, 3, 1, 2]


def find_min_diff(my_list):
    if len(set(my_list)) != len(my_list):  # See note 1
        return 0
    else:
        temp = sorted(my_list)
        my_min = float('inf')
        for i, j in zip(temp [:-1], temp [1:]):
            diff = abs(i - j)
            if diff < my_min:
                my_min = diff
        return my_min

print(find_min_diff(A))  # -> 0

Notes:

1: Converting to set removes the duplicates so if the corresponding set has less elements than the original list it means that there is at least one duplicate value. But that necessarily means that the min absolute difference is 0 and we do not have to look any further.

I would be willing to bet that this is the fastest approach for all lists that would return 0.

2 of 5
4

You should not be subtracting 1 from j in the inner loop as you end up skipping the comparison of the last 2. It is better to make the adjustments in the loop ranges, rather than subtracting 1 (or not) in the loop code:

A = [2, 7, 5, 9, 3, 1, 2]

N = 7

mint = 1000

for i in range (0, N-1):
    for j in range (i+1, N):
        if (abs(A[i] - A[j]) < mint):
            mint = abs(A[i] - A[j])
            print(i, j)
            print(mint)
print(mint) # 0

I have also avoided the use of a built-in function name min.


To avoid the arbitrary, magic, number 1000, you can perform an initial check against None:

A = [2, 7, 5, 9, 3, 1, 2]

N = 7

mint = None

for i in range (0, N-1):
    for j in range (i+1, N):
        if mint is None:
            mint = abs(A[i] - A[j])
        elif (abs(A[i] - A[j]) < mint):
            mint = abs(A[i] - A[j])
            print(i, j)
            print(mint)
print(mint) # 0
🌐
Programiz
programiz.com › python-programming › methods › built-in › abs
Python abs()
For floating numbers - the floating absolute value is returned
🌐
GeeksforGeeks
geeksforgeeks.org › python-absolute-value-of-list-elements
Absolute Value of List Elements | GeeksforGeeks
January 29, 2025 - We are given a list containing negative values we need to find the absolute value of all the values present inside the list. For example, we are having a list li = [-1, 2, -3, 4, -5] we need to convert all the negative values to its absolute ...
🌐
datagy
datagy.io › home › python posts › python absolute value: abs() in python
Python Absolute Value: Abs() in Python • datagy
December 15, 2022 - Numpy arrays are list-like structures, but they come with a number of different built-in methods than Python lists do. For example, one the numpy functions, np.abs(), takes a numpy array and converts all of its numbers to their absolute value.
🌐
W3Schools
w3schools.com › python › ref_func_abs.asp
Python abs() Function
Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... The abs() function returns the absolute value of the specified number.
🌐
freeCodeCamp
freecodecamp.org › news › python-absolute-value-python-abs-tutorial
Python Absolute Value – Python abs Tutorial
June 20, 2022 - So, let's take the complex number 3 + 4j for example. You would need to calculate the square root of the squares of the numbers from the real part (3) and the imaginary part 4: \(\sqrt{3^2 + 4^2} = 5\) In Python, this is how you would use a ...
🌐
Note.nkmk.me
note.nkmk.me › home › python
Get Absolute Values in Python: abs(), math.fabs() | note.nkmk.me
May 11, 2025 - Duck typing with hasattr() and ... a simple example where abs() always returns 100: class MyClass: def __abs__(self): return 100 mc = MyClass() print(abs(mc)) # 100 ·...
🌐
LearnDataSci
learndatasci.com › solutions › python-absolute-value
Python Absolute Value – abs() for real and complex numbers – LearnDataSci
The absolute value of a number refers to that value's magnitude, regardless of whether it is positive or negative. For example, the absolute value of -5 is 5. Below is the syntax for using the abs() function to determine the absolute value of a number in Python:
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › abs-in-python
abs() in Python - GeeksforGeeks
August 30, 2024 - # floating point number float_number = -54.26 print('Absolute value of float is:', abs(float_number)) ... In this example, we will pass Python complex number into the abs() function and it will return an absolute value.
🌐
Real Python
realpython.com › python-absolute-value
How to Find an Absolute Value in Python – Real Python
June 4, 2025 - Yes, you can find the absolute value of a complex number in Python using the abs() function. This function calculates the magnitude of the complex number as a floating-point value. How can you calculate the absolute value of a list of numbers in Python?Show/Hide
🌐
w3resource
w3resource.com › python › built-in-function › abs.php
Python: abs() function - w3resource
August 19, 2022 - >>> type(-2) <class 'int'> >>> ... 'float'> >>> ... nums = [12,30,-33,-22,77,-100] print("Original list:") print(nums) print("\nAbsolute values of the above numbers:") print([abs(x) for x in nums])...
🌐
Real Python
realpython.com › ref › builtin-functions › abs
abs() | Python’s Built-in Functions – Real Python
>>> temperatures = [22, 25, 18, 30, 15, 28, 21] >>> average_temp = sum(temperatures) / len(temperatures) >>> deviations = [abs(temp - average_temp) for temp in temperatures] >>> print("Absolute deviations:", *deviations, sep="\n") Absolute deviations: 0.7142857142857153 2.2857142857142847 4.714285714285715 7.285714285714285 7.714285714285715 5.285714285714285 1.7142857142857153 · In this example, you compute the temperature deviations from the average temperature using abs()....
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › abs in python
Master Python abs() Function: Syntax, Uses, and Examples - upGrad
November 30, 2019 - In this example, the list comprehension uses the abs() function to identify quarters where the profit margin deviates significantly from the threshold, indicating potential issues that require attention.
🌐
Server Academy
serveracademy.com › blog › python-absolute-value-abs-tutorial
Python Absolute Value Abs() Tutorial - Server Academy
November 12, 2024 - For example, the absolute value of -5 is 5, and the absolute value of 5 is also 5. Absolute values are often used in scenarios where only the magnitude of a number matters, such as distance measurements, loss functions in machine learning, and ...
🌐
BeginnersBook
beginnersbook.com › 2019 › 03 › python-abs-function
Python abs() Function with examples
# integer number num = -5 ... as an argument to abs() function, it returns the magnitude of the complex number. The magnitude of a complex number a + bj is equal to √a2+b2. # complex number cnum = 4 - 5j print('Absolute value of 4 - 5j is:', abs(cnum)) cnum2 = 3 ...
🌐
Tutorialspoint
tutorialspoint.com › python › number_abs.htm
Python abs() function
Absolute Value of an Integer: 34 Absolute Value of an Float: 154.32 · If we pass a complex number as an argument to this function, the return value will be the magnitude of this complex number.
🌐
Python documentation
docs.python.org › 3 › library › functions.html
Built-in Functions — Python 3.14.3 documentation
3 weeks ago - The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.,,,, Built-in Functions,,, A, abs(), aiter(), all(), a...
🌐
Javatpoint
javatpoint.com › python-abs-function
abs() in Python | Python abs() Function with Examples - Javatpoint
October 24, 2025 - abs() in Python | Python abs() Function with Examples on Python, Built in, Functions, abs Function, all Function, bin Function, bool Function, python Functions, new sum Function, bytes Function, new callable Function etc.