[Python] How do I remove duplicate values from a list while maintaining order in Python?...

Discussão em 'Python' iniciado por Stack, Maio 22, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to remove duplicate items from a list in Python, but I want to keep the original order of the elements. For example, if I have:

    python Copy Edit my_list = [1, 2, 2, 3, 1, 4, 3] I want the output to be:

    python Copy Edit [1, 2, 3, 4] I tried using set(), but it doesn't preserve the order:

    python Copy Edit list(set(my_list)) This gives me different results each time, and the order is not what I want.

    What is the most efficient or Pythonic way to do this?

    I tried using list(set(my_list)) to remove duplicates, but it returned the elements in a random order. I expected the output to keep the first occurrence of each value and maintain the original sequence, like [1, 2, 3, 4]. Instead, I got something like [1, 2, 3, 4] but in a different order each time, which is not what I want.

    Continue reading...

Compartilhe esta Página