Junior — Middle
How can duplicate elements be removed from a list collection?
sobes.tech AI
Answer from AI
To remove duplicate elements from a list in Python, you can use several methods:
- Convert the list to a set, since sets do not contain duplicates, and then back to a list:
lst = [1, 2, 2, 3, 4, 4, 5]
lst_unique = list(set(lst))
print(lst_unique) # The order of elements may change
- If the order of elements is important, you can use a loop with a check or use
dict.fromkeys(), which preserves order starting from Python 3.7:
lst = [1, 2, 2, 3, 4, 4, 5]
lst_unique = list(dict.fromkeys(lst))
print(lst_unique) # [1, 2, 3, 4, 5]
- Use a generator with an auxiliary set to track already seen elements:
lst = [1, 2, 2, 3, 4, 4, 5]
seen = set()
lst_unique = [x for x in lst if not (x in seen or seen.add(x))]
print(lst_unique) # [1, 2, 3, 4, 5]
All these methods efficiently remove duplicates from a list.