Last active
June 11, 2018 09:30
-
-
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)
This file contains 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
# 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