[Python] What is the pythonic way to detect the last element in a 'for' loop?

Discussão em 'Python' iniciado por Stack, Junho 28, 2025.

  1. Stack

    Stack Membro Participativo

    How can I treat the last element of the input specially, when iterating with a for loop? In particular, if there is code that should only occur "between" elements (and not "after" the last one), how can I structure the code?

    Currently, I write code like so:

    for i, data in enumerate(data_list):
    code_that_is_done_for_every_element
    if i != len(data_list) - 1:
    code_that_is_done_between_elements


    How can I simplify or improve this?

    Continue reading...

Compartilhe esta Página