Skip to content

Instantly share code, notes, and snippets.

@jpclipffel
Last active June 11, 2018 09:30
Show Gist options
  • Save jpclipffel/377a9fd89f9e267a94f4 to your computer and use it in GitHub Desktop.
Save jpclipffel/377a9fd89f9e267a94f4 to your computer and use it in GitHub Desktop.
Remove duplicate items from a list in one line (with and without order preservation)
# Data set.
data = ['a', 'b', 'b', 'c', 'd', 'e', 'a', 'f', 'e']
# Solution 1 - Keep first occurence only (preserves the list order)
print([ v for p, v in enumerate(data) if v not in data[0:data.index(v, p)] ])
# Solution 2 - Keep last occurence only (preserves the list order)
print([ v for p, v in enumerate(data) if v not in data[data.index(v, p)+1:] ])
# Solution 3 - Using 'set' (do **not** preserve the list order !)
print(list(set(data)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment