Python – Nearest occurrence between two elements in a List

• Last Updated : 11 Jun, 2021

Given a list and two elements, x and y find the nearest occurrence index of element x from element y.

Input : test_list = [2, 4, 5, 7, 8, 6, 3, 8, 7, 2, 0, 9, 4, 9, 4], x = 4, y = 6
Output : 1
Explanation : 4 is found at 1, 12 and 14th index, 6 is at 5th index, nearest is 1st index.

Input : test_list = [2, 4, 5, 7, 8, 6, 3, 8, 7, 2, 0, 9, 4, 9, 4], x = 7, y = 6
Output : 3
Explanation : 7 is found at 3rd and 8th index, 6 is at 5th index, nearest is 3rd index.

Method : Using list comprehension + loop + index()

In this, we find all indices of y using list comprehension, and then get index of x using index(), post that loop is used to get index difference, the nearest index is returned as result.

Python3

 # Python3 code to demonstrate working of# Nearest occurrence of x from y in List# Using list comprehension + loop + index()  # function to find index of nearest# occurrence between two elementsdef nearestOccurrenceIndex(test_list, x, y):     # checking if both elements are present in list    if x not in test_list or y not in test_list:        return -1    # getting indices of x    x_idx = [idx for idx in range(len(test_list)) if test_list[idx] == x]     # getting y index    y_idx = test_list.index(y)     # getting min_dist index    min_dist = 1000000    res = None    for ele in x_idx:         # checking for min ele, and updating index        if abs(ele - y_idx) < min_dist:            res = ele            min_dist = abs(ele - y_idx)    return res  # initializing listinput_list = [2, 4, 5, 7, 8, 6, 3, 8, 4, 2, 0, 9, 4, 9, 4] # printing original listprint("The original list is : " + str(input_list)) # initializing xx = 4 # initializing yy = 6 # printing resultprint("Minimum distance index: ", nearestOccurrenceIndex(input_list, x, y))

Output:

The original list is : [2, 4, 5, 7, 8, 6, 3, 8, 4, 2, 0, 9, 4, 9, 4]
Minimum distance index:  8

My Personal Notes arrow_drop_up
{"ft_lang_label":"__label__en","ft_lang_prob":0.74558514,"math_prob":0.9850673,"size":1872,"snap":"2022-05-2022-21","text_gpt3_token_len":672,"char_repetition_ratio":0.13490364,"word_repetition_ratio":0.13451776,"special_character_ratio":0.3696581,"punctuation_ratio":0.22610722,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.98487383,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-01-21T02:47:51Z\",\"WARC-Record-ID\":\"<urn:uuid:839af521-5af0-41f6-be42-193be08456b1>\",\"Content-Length\":\"116434\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:4e685489-7c45-45f4-9fe0-dc85d0cfc667>\",\"WARC-Concurrent-To\":\"<urn:uuid:404b774c-3c21-4e3b-840d-98cc716db6a0>\",\"WARC-IP-Address\":\"23.222.12.51\",\"WARC-Target-URI\":\"https://www.geeksforgeeks.org/python-nearest-occurrence-between-two-elements-in-a-list/?ref=rp\",\"WARC-Payload-Digest\":\"sha1:Q2YMF7CXGFXXVIZS67CXYL6R3QEZSEQ3\",\"WARC-Block-Digest\":\"sha1:TEVHIDCMYFJVGLQ3X7OBIAKN37HL5ZCD\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-05/CC-MAIN-2022-05_segments_1642320302715.38_warc_CC-MAIN-20220121010736-20220121040736-00401.warc.gz\"}"}