Use enumerate() function to access the next item in a list in python for a loop. The for loop allows to access the variables next to the current value of the indexing variable in the list.
Python example for loop get next item
lst = [1, 2, 3, 4, 5] for index, elem in enumerate(lst): if index + 1 < len(lst) and index - 1 >= 0: curr_el = elem - 1 next_el = lst[index] print(curr_el, "Next ->", next_el)
Function to get next value from list
You have to pass the value to find the next element in the given list.
lst = [1, 2, 3, 4, 5] def getNext(x): next_el = None for index, elem in enumerate(lst): if index + 1 < len(lst) and index - 1 >= 0: curr_el = elem - 1 if x == curr_el: next_el = lst[index] return next_el print(getNext(2))
Do comment if you have any doubts and suggestions on this Python for loop topic.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.