Junior — Middle
What data structure type is preferred for eliminating duplicate elements in a collection?
sobes.tech AI
Answer from AI
To remove duplicate elements in a collection in Python, it is preferable to use the set data type.
set is an unordered collection of unique elements. When adding elements to a set, duplicates are automatically removed.
Example:
items = [1, 2, 2, 3, 4, 4, 5]
unique_items = set(items)
print(unique_items) # Outputs: {1, 2, 3, 4, 5}
If you need to preserve the order of elements without duplicates, you can use dict.fromkeys() or collections.OrderedDict (in Python 3.7+ regular dict preserves order):
items = [1, 2, 2, 3, 4, 4, 5]
unique_ordered = list(dict.fromkeys(items))
print(unique_ordered) # [1, 2, 3, 4, 5]
Thus, for simple duplicate removal, set is the most suitable and efficient solution.