Junior — Middle
How can you eliminate duplicate elements in a data collection?
sobes.tech AI
Answer from AI
In Python, there are several ways to remove duplicate elements from a collection (such as a list):
- Converting to a set — a set contains only unique elements, but the order is lost:
items = [1, 2, 2, 3, 4, 4, 5]
unique_items = list(set(items))
- Using dict.fromkeys() — preserves the order of appearance of elements (starting from Python 3.7):
items = [1, 2, 2, 3, 4, 4, 5]
unique_items = list(dict.fromkeys(items))
- Using a loop with a check — suitable for more complex conditions or custom objects:
unique_items = []
seen = set()
for item in items:
if item not in seen:
unique_items.append(item)
seen.add(item)
The choice of method depends on whether you need to preserve order and the data type.