-8

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
Jamiu S.
  • 5,257
  • 5
  • 12
  • 34

2 Answers2

-1

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.

user19077881
  • 3,643
  • 2
  • 3
  • 14
  • It is worth adding a check to see if this element is the last one, so as not to go beyond the list: if pos+1 – stukituk Jan 15 '23 at 15:12
-1

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"

Devesh Joshi
  • 9
  • 1
  • 5