Skip to content

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.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

1 thought on “Python for loop next item | Example code”

  1. Hi Rohit. Thanks for the example above, but it doesn’t really work outside of successive numerical values. If someone wanted to look forward in a list of strings, this would’t help. As an example, replace your lst with lst = [‘A’, ‘B’, ‘C’, ‘D’, ‘E’].
    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

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