Why does a set remove duplicate values but not keep my original order?
Quick answer
A set is designed to hold unique values, not to preserve the order of the sequence you started with. Python’s documentation describes sets as unordered, so their iteration or printed order may look unexpected [S1]. If original position matters, keep a list as your result. You can use a separate set to check which values you have already added, while the list records them in first-seen order.
The question, the details, the next step.
A practical checklist
Decide whether the result needs first-seen order, sorted order, or only unique membership.
Write down the expected output for an example containing a repeated value.
Keep a list as the result when original sequence order matters.
Use a set separately to track values already encountered.
Use
sorted(set(values))only when sorted unique output—not original order—is intended.
A few more useful answers
Does a set always print values in a different order from the input?
No. Its displayed order may sometimes look familiar, but a set is unordered, so that appearance is not a promise you should rely on [S1].
Will sorting unique values preserve their original positions?
No. Sorting gives a sorted order, not the input’s first-seen order [S1]. Use a list-based result if first appearance matters.
Why keep both a list and a set?
They have different jobs in this pattern: the list records the order you want to return, while the set records which values have already appeared.
Sources
References used for this guide.
- [S1] Data Structures — Sets and ordering docs.python.org · Checked
