[Python] How can I remove only consecutive duplicate elements from a list in Python?

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

  1. Stack

    Stack Membro Participativo

    I have a list of elements where I want to remove only consecutive duplicates, not all duplicates.

    For example: data = [1, 1, 2, 2, 2, 3, 1, 1]

    I want to get: [1, 2, 3, 1]

    This is different from using set() or dict.fromkeys(), I don’t want to remove all duplicates, just ones that are repeated right after each other.

    What I tried:

    result = []
    for i in data:
    if not result or result[-1] != i:
    result.append(i)


    This works, but I wonder: Is this the cleanest approach, and does it scale well for large lists?

    Continue reading...

Compartilhe esta Página