Python for loop next item | Example code

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

Simple example code accessing Next Element While iterating.

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)

Output:

Python for loop next item

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))

Output: 3

Do comment if you have any doubts and suggestions on this Python for loop topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.