How to find the nearest element in a list

Question:

I want to find the element of a given index and the element near to it from a large python list like this:

list = ['askdjh', 'afgld', 'asf' ,'asd', '623gfash', 'fhd', 'hfdjs']

And I chose ‘asd’ :

number = 4
item near it = 623gfash
Asked By: Marius Radulescu

||

Answers:

Use

pos = my_list.index('asd')
nearest = my_list[pos + 1]

Note pos is 3 for the 4th element as Python is 0- based. Note avoid using list for variables as this name has a special meaning in Python.

Answered By: user19077881

Try below

ind=ls.index("asd")
if ind<len(ls)-1:
   print(f"{ind}",ls.__getitem__(ind+1))
else:
   print(f"{ind}", ls.__getitem__(ind - 1))

ind, will give you the index of the chosen obj, and using that index only you can fetch closest obj by adding or subtracting 1 from the "ind"

Answered By: Devesh Joshi

You have to use list.index if you want to find the actual index of the element given the element

I’m not sure what do you mean by the nearest element, please clarify that in your description if your intent was something else otherwise you can delete this question if you wish.

Also this is a duplicate question.

And note that you are rename the pythons list function and the previous question is just doing ls[index+/-1] there.

Answered By: Yaser Jafari J
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.