Given an input sequence of any type (list/string/range) how do I find the next item in the input following the specified item?
Also, if the item isn't present or nothing follows it, the function should return None
.
I tried converting input type to a list and then finding the position from a list, then getting the next item but this does not work for all input types. I have written something but I know it is not pythonic and it also times out. (codewars challenge: https://www.codewars.com/kata/542ebbdb494db239f8000046/train/python)
My attempt:
def next_item(xs, item):
xs_list = list(xs)
if item in xs_list:
position = xs_list.index(item)
try:
return xs_list[position+1]
except IndexError:
return None
else:
return None
Desired results:
next_item([1, 2, 3, 4, 5, 6, 7, 8], 5)
# 6)
next_item(['a', 'b', 'c'], 'd')
# None)
next_item(['a', 'b', 'c'], 'c')
# None)
next_item('testing', 't')
# # 'e')
next_item(iter(range(1, 3000)), 12)
# , 13)