Python – Nearest occurrence between two elements in a List

When you need to find the nearest occurrence between two elements in a list, you can create a function that calculates the minimum distance between all occurrences of the first element and the target element. This approach uses list comprehension and the abs() function to find the closest match.

Example

Here's how to find the index of the nearest occurrence ?

def nearest_occurrence_list(my_list, x, y):
    if x not in my_list or y not in my_list:
        return -1
    
    x_indices = [index for index in range(len(my_list)) if my_list[index] == x]
    y_index = my_list.index(y)
    
    min_dist = float('inf')
    result = None
    
    for element in x_indices:
        if abs(element - y_index) < min_dist:
            result = element
            min_dist = abs(element - y_index)
    
    return result

my_list = [12, 24, 15, 17, 28, 26, 13, 28, 14, 12, 20, 19, 24, 29, 14]
print("The list is:")
print(my_list)

x = 14
print("The value of x is:")
print(x)

y = 26
print("The value of y is:")
print(y)

print("The nearest occurrence index is:")
print(nearest_occurrence_list(my_list, x, y))
The list is:
[12, 24, 15, 17, 28, 26, 13, 28, 14, 12, 20, 19, 24, 29, 14]
The value of x is:
14
The value of y is:
26
The nearest occurrence index is:
8

How It Works

The function works by following these steps:

  • First, it checks if both elements exist in the list using the not in operator

  • It finds all indices where element x appears using list comprehension

  • It gets the index of element y using the index() method

  • It calculates the absolute distance between each occurrence of x and y

  • It returns the index of x that has the minimum distance to y

Alternative Approach Using min()

You can simplify the solution using Python's built-in min() function ?

def nearest_occurrence_simple(my_list, x, y):
    if x not in my_list or y not in my_list:
        return -1
    
    x_indices = [i for i, val in enumerate(my_list) if val == x]
    y_index = my_list.index(y)
    
    return min(x_indices, key=lambda i: abs(i - y_index))

my_list = [12, 24, 15, 17, 28, 26, 13, 28, 14, 12, 20, 19, 24, 29, 14]
x = 14
y = 26

print("Nearest occurrence index:")
print(nearest_occurrence_simple(my_list, x, y))
Nearest occurrence index:
8

Conclusion

Finding the nearest occurrence between two elements involves calculating distances between all possible pairs and selecting the minimum. The min() function with a key parameter provides a more concise solution than manual iteration.

Updated on: 2026-03-26T01:18:52+05:30

344 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements