Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 inoperatorIt finds all indices where element
xappears using list comprehensionIt gets the index of element
yusing theindex()methodIt calculates the absolute distance between each occurrence of
xandyIt returns the index of
xthat has the minimum distance toy
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.
