Hey everyone! π
Today, we're tackling a list manipulation problem: Removing Duplicates while Maintaining Order.
The Problem
The goal is to write a function that removes duplicates from a list while maintaining the original order of elements.
Example:
-
remove_duplicates([1, 2, 2, 3, 1, 4])should return[1, 2, 3, 4]
The Solution
Here is the Python implementation:
def remove_duplicates(lst):
"""
Removes duplicates from a list while maintaining order.
"""
seen = set()
result = []
for i in lst:
if i not in seen:
seen.add(i)
result.append(i)
return result
# Test case
print(remove_duplicates([1, 2, 2, 3, 1, 4]))
# Output: [1, 2, 3, 4]
Code Breakdown
Let's walk through the code line by line:
-
def remove_duplicates(lst):- Defines a function named
remove_duplicatesthat takes one parameterlst(a list).
- Defines a function named
-
seen = set()- Creates an empty set called
seento keep track of unique elements we've encountered. Using a set allows for efficient O(1) lookups.
- Creates an empty set called
-
result = []- Creates an empty list called
resultto store the final list without duplicates.
- Creates an empty list called
-
for i in lst:- Starts a loop that iterates through each element in the input list
lst.
- Starts a loop that iterates through each element in the input list
-
if i not in seen:- Checks if the current element
iis not in theseenset (i.e., it's the first time we're seeing this element).
- Checks if the current element
-
seen.add(i)- If the element is not in
seen, adds it to the set to mark it as seen.
- If the element is not in
-
result.append(i)- Appends the element to the
resultlist to maintain the order of first occurrence.
- Appends the element to the
-
return result- Returns the final list with duplicates removed, in the order of their first appearance.
Example Walkthrough with [1, 2, 2, 3, 1, 4]
-
i = 1: Not in seen β add to seen and result- seen:
{1} - result:
[1]
- seen:
-
i = 2: Not in seen β add to seen and result- seen:
{1, 2} - result:
[1, 2]
- seen:
-
i = 2: Already in seen β skip -
i = 3: Not in seen β add to seen and result- seen:
{1, 2, 3} - result:
[1, 2, 3]
- seen:
-
i = 1: Already in seen β skip -
i = 4: Not in seen β add to seen and result- seen:
{1, 2, 3, 4} - result:
[1, 2, 3, 4]
- seen:
Final result: [1, 2, 3, 4]
Happy coding! π»
Top comments (0)