Skip to content

Instantly share code, notes, and snippets.

@Rudxain
Created March 14, 2023 23:34
Show Gist options
  • Save Rudxain/40f2123bbf542d144d06b737036c06b2 to your computer and use it in GitHub Desktop.
Save Rudxain/40f2123bbf542d144d06b737036c06b2 to your computer and use it in GitHub Desktop.
fn to remove duplicate ocurrences from a list, in either order (preserves original order), not in-place
from typing import Final, TypeVar
T = TypeVar('T')
def remove_dupes(inp: list[T], keep_last: bool = False) -> list[T]:
'''
creates a list from input,
such that all ocurrences (but 1) of each value are removed
(order is preserved).
if `keep_last`,
it removes all but the last ocurrence,
otherwise all but the 1st
'''
seen: Final[set[T]] = set()
out: Final[list[T]] = []
for x in (reversed(inp) if keep_last else inp):
if x not in seen:
seen.add(x)
out.append(x)
if keep_last:
out.reverse()
return out
# LICENSE: https://unlicense.org
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment