Junior — Middle
What type of data is recommended to be used to eliminate duplicate elements in a collection?
sobes.tech AI
Answer from AI
To remove duplicate elements from a collection in Python, it is recommended to use the set data type. A set automatically stores only unique elements, making it easy to eliminate duplicates.
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, you can use dict.fromkeys() or collections.OrderedDict (in Python versions before 3.7), or simply use dict in Python 3.7+ since dictionaries preserve insertion order:
items = [1, 2, 2, 3, 4, 4, 5]
unique_items_ordered = list(dict.fromkeys(items))
print(unique_items_ordered) # Outputs: [1, 2, 3, 4, 5]