Remove duplicate values in list
suggest changeRemoving duplicate values in a list can be done by converting the list to a set (that is an unordered collection of distinct objects). If a list data structure is needed, then the set can be converted back to a list using the function list():
names = ["aixk", "duke", "edik", "tofp", "duke"]
list(set(names))
# Out: ['duke', 'tofp', 'aixk', 'edik']
Note that by converting a list to a set the original ordering is lost.
To preserve order, build a dict (insertion order is guaranteed since Python 3.7) or an OrderedDict. Call list on it: .keys() is a view, not a list.
list(dict.fromkeys(names))
# Out: ['aixk', 'duke', 'edik', 'tofp']
import collections
list(collections.OrderedDict.fromkeys(names))
# Out: ['aixk', 'duke', 'edik', 'tofp']
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents