Reputation: 408
A list of unique elements can be attained by converting a list to a dictionary or a set, then back to a list.
>>> original_list = [1,2,3,4,5,6,7,8,9,2,4,6,8]
>>> original_list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 4, 6, 8]
>>>
>>> unique_via_set = list(set(original_list))
>>> unique_via_dict = list(dict.fromkeys(original_list))
>>>
>>> unique_via_set
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> unique_via_dict
[1, 2, 3, 4, 5, 6, 7, 8, 9]
^Python 3.7.3
Sub Questions:
Note: I'm not looking for the best or fastest way to get unique elements from a list, I am looking to compare the two methods above
Edit: Again, I am not looking for HOW to remove duplicates, I am merely looking for the practical differences in the methods above, if any
Upvotes: 1
Views: 61
Reputation: 114330
While the implementations of the hash tables for dictionaries and sets may differ slightly, you will not see a functional difference between the keys of the dictionary and the set. The only major difference will be that the dictionary allocates a bunch of values referencing None
, which the set does not need. That might make the dictionary implementation less efficient, since it is unnecessary overhead.
Upvotes: 2