When it is required to display nearest occurrence between two elements in a list, a method is defined that takes three parameters. It uses the ‘not in’ operator, and the list comprehension to determine the result.
Below is a demonstration of the same −
def nearest_occurence_list(my_list, x, y): if x not in my_list or y not in my_list: return -1 x_index = [index for index in range(len(my_list)) if my_list[index] == x] y_index = my_list.index(y) min_dist = 1000000 result = None for element in x_index: 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 result is :") print(nearest_occurence_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 result is : 8
A method named ‘nearest_occurence_list’ is defined that takes three parameters.
If the second or third parameter is not present in first parameter, then -1 is returned.
A list comprehension is used to iterate over the elements and get the length of the list if the list contains the first parameter.
This is assigned to variable one.
The index of the second parameter is determined.
The elements within variable one are iterated over, and the difference between the element and index of y is compared with a specific value.
Depending on this, the result is returned.
Outside the method, a list is defined and displayed on the console.
The values for x and y are defined and displayed on the console.
The method is called by passing the required parameters.
This is the output that is displayed on the console.