user15590480
user15590480

Reputation: 97

Python: Get next element from the list based on input?

I have a list

elem_list = ['a','b','c','d']

I'm trying to get next element from the list based on input

input_val = 'c'
out_data = 'd'

input_val = 'a'
out_data = 'b'

input_val = 'd'
out_data = ''

Upvotes: 0

Views: 299

Answers (1)

GoodDeeds
GoodDeeds

Reputation: 8517

Assuming that input_val is guaranteed to be present exactly once in the list, you can use:

out_data = ''
elem_index = elem_list.index(input_val)
if elem_index != len(elem_list)-1:
    out_data = elem_list[elem_index+1]

Here, you are first finding the index of the input in the list, and setting the output to be the value at the next index unless it is the last element, in which case you set it as the empty string.

Upvotes: 1

Related Questions