Created
June 29, 2018 10:42
-
-
Save djm/53618ae68b6e01ed9e50b2564ce1a3ca to your computer and use it in GitHub Desktop.
Python: remove duplicates from a list/sequence while retaining the original order
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from typing import List, Sequence | |
| def unique_with_order(sequence: Sequence) -> List: | |
| """ | |
| Returns the original sequence as a list with duplicates removed | |
| but, unlike simply using set, the original order is retained. | |
| """ | |
| seen = set() | |
| return [x for x in sequence if not (x in seen or seen.add(x))] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import pytest | |
| from your_path import unique_with_order | |
| @pytest.mark.parametrize('input_sequence,expected', [ | |
| ((1, 3, 2, 2, 1), [1, 3, 2]), | |
| (['a', 'z', 't', 't', 'tt', 'e'], ['a', 'z', 't', 'tt', 'e']) | |
| ]) | |
| def test_unique_with_order(input_sequence, expected): | |
| assert unique_with_order(input_sequence) == expected |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment