Python Program to Remove Duplicates from List
list(set(your_list)), or by using a loop to keep only unique items.Examples
How to Think About It
Algorithm
Code
def remove_duplicates(lst): unique_list = [] for item in lst: if item not in unique_list: unique_list.append(item) return unique_list # Example usage my_list = [1, 2, 2, 3, 4, 4, 5] print(remove_duplicates(my_list))
Dry Run
Let's trace the list [1, 2, 2, 3, 4, 4, 5] through the code
Start with empty unique_list
unique_list = []
Check first item 1
1 not in unique_list, so add 1 -> unique_list = [1]
Check second item 2
2 not in unique_list, add 2 -> unique_list = [1, 2]
Check third item 2
2 already in unique_list, skip
Check fourth item 3
3 not in unique_list, add 3 -> unique_list = [1, 2, 3]
Check fifth item 4
4 not in unique_list, add 4 -> unique_list = [1, 2, 3, 4]
Check sixth item 4
4 already in unique_list, skip
Check seventh item 5
5 not in unique_list, add 5 -> unique_list = [1, 2, 3, 4, 5]
| Iteration | Current Item | unique_list |
|---|---|---|
| 1 | 1 | [1] |
| 2 | 2 | [1, 2] |
| 3 | 2 | [1, 2] |
| 4 | 3 | [1, 2, 3] |
| 5 | 4 | [1, 2, 3, 4] |
| 6 | 4 | [1, 2, 3, 4] |
| 7 | 5 | [1, 2, 3, 4, 5] |
Why This Works
Step 1: Using a loop to check duplicates
The code goes through each item and checks if it is already in the new list using if item not in unique_list. This ensures only unique items are added.
Step 2: Building a new list
Instead of changing the original list, the code creates a new list to store unique items, which keeps the order of first appearances.
Step 3: Returning the result
After checking all items, the new list with no duplicates is returned and printed.
Alternative Approaches
def remove_duplicates_set(lst): return list(set(lst)) print(remove_duplicates_set([1, 2, 2, 3, 4, 4, 5]))
def remove_duplicates_dict(lst): return list(dict.fromkeys(lst)) print(remove_duplicates_dict([1, 2, 2, 3, 4, 4, 5]))
Complexity: O(n^2) time, O(n) space
Time Complexity
The main method uses a loop with if item not in unique_list, which takes O(n) time for each check, leading to O(n^2) overall for n items.
Space Complexity
It uses extra space for the new list to store unique items, so O(n) space is needed.
Which Approach is Fastest?
Using set() conversion is fastest with O(n) time but loses order. Using dict.fromkeys() is also O(n) and keeps order, making it a good balance.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Loop with list check | O(n^2) | O(n) | Small lists, order preserved |
| Set conversion | O(n) | O(n) | Fastest, order not preserved |
| dict.fromkeys() | O(n) | O(n) | Fast and order preserved |
dict.fromkeys() to remove duplicates while keeping the original order in a simple way.