DEV Community

Esteban S.
Esteban S.

Posted on

How to easily know when we are at the last element inside a loop

An easy way to detect if we are at the last element of a python vector

First, we will create a function that will return a generator using the yield keyword.

from typing import Union, Set, List, Tuple, Any

Vectors = Union[Tuple, List, Set]

def lookthelast(items: Vectors) -> Tuple[Any, bool]:
    lenght_items = len(items)

    for index, value in enumerate(items):
        if index == (lenght_items - 1):
            yield value, True; break

        yield value, False
Enter fullscreen mode Exit fullscreen mode

you can do this directly in your use case, but if we encapsulate this, we improve readability. it only imports the function and we avoid rewriting this code every loop.

An use case example:

numbers = ["one", "two", "three"]

for value, is_the_last in lookthelast(numbers):
    if is_the_last:
        print("this is the last element -> " + value)
        break

    print(value)
Enter fullscreen mode Exit fullscreen mode

👉 execute this example here

Top comments (0)