Python Program to Find Unique Elements Using Set
unique_elements = set(your_list), which removes duplicates and keeps only unique values.Examples
How to Think About It
Algorithm
Code
def find_unique_elements(lst): unique_elements = set(lst) return unique_elements # Example usage sample_list = [1, 2, 2, 3, 4, 4, 5] print(find_unique_elements(sample_list))
Dry Run
Let's trace the list [1, 2, 2, 3, 4, 4, 5] through the code
Input list
lst = [1, 2, 2, 3, 4, 4, 5]
Convert list to set
unique_elements = set([1, 2, 2, 3, 4, 4, 5]) results in {1, 2, 3, 4, 5}
Return unique elements
Return {1, 2, 3, 4, 5}
| Iteration | Current Element | Set Contents |
|---|---|---|
| 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 set removes duplicates
A set in Python automatically keeps only one copy of each element, so converting a list to a set removes repeated items.
Step 2: Conversion is simple and fast
Using set() is a built-in, efficient way to get unique elements without writing loops.
Step 3: Result is a set of unique elements
The output is a set containing only unique values from the original list.
Alternative Approaches
def find_unique_with_loop(lst): unique = [] for item in lst: if item not in unique: unique.append(item) return unique print(find_unique_with_loop([1, 2, 2, 3, 4, 4, 5]))
def find_unique_with_dict(lst): unique = list(dict.fromkeys(lst)) return unique print(find_unique_with_dict([1, 2, 2, 3, 4, 4, 5]))
Complexity: O(n) time, O(n) space
Time Complexity
Converting a list to a set takes O(n) time because it processes each element once.
Space Complexity
The set stores unique elements, so in the worst case it uses O(n) space if all elements are unique.
Which Approach is Fastest?
Using set() is fastest for removing duplicates but does not preserve order; dictionary keys keep order but use more memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Using set() | O(n) | O(n) | Fast duplicate removal, order not needed |
| Loop with list | O(n²) | O(n) | Preserving order, small lists |
| Dictionary keys | O(n) | O(n) | Preserving order, faster than loop |
set() to quickly remove duplicates but remember sets do not keep order.