π Day 49/150 – Remove Duplicates from a List in Python
Removing duplicates means keeping only unique elements in a list.
Example:
[1, 2, 2, 3, 4, 4, 5] → [1, 2, 3, 4, 5]
Let’s explore different ways to remove duplicates π
πΉ Method 1 – Using set()
This is the simplest and fastest method.
However, it does not preserve the original order of elements.
πΉ Method 2 – Using Loop
numbers = [1, 2, 2, 3, 4, 4, 5] unique = [] for num in numbers: if num not in unique: unique.append(num) print("Unique List:", unique)
πΉ Method 3 – Using dict.fromkeys()
numbers = [1, 2, 2, 3, 4, 4, 5]
unique = list(dict.fromkeys(numbers))
print("Unique List:", unique)This is a clean and efficient method that also maintains order (Python 3.7+).πΉ Method 4 – Using List Comprehension
numbers = [1, 2, 2, 3, 4, 4, 5] unique = [] [unique.append(x) for x in numbers if x not in unique] print("Unique List:", unique)
This works correctly, but it’s not recommended because list comprehensions are meant for creating lists, not for side effects.
πΉ Output
Unique List: [1, 2, 3, 4, 5]
π₯ Key Takeaways
✔️ Use set() for speed when order doesn’t matter
✔️ Use loops ordict.fromkeys()to preserve order
✔️ Avoid using list comprehension for side effects
✔️ Choose the method based on your requirement


0 Comments:
Post a Comment