To remove duplicates from a list in Python while maintaining the order of elements, you can use a combination of a for loop and a set to keep track of seen elements.
In this example,
original_list
with some duplicate elements.unique_list
to store the elements without duplicates.seen
to keep track of elements that have already been added to unique_list
.original_list
.seen
set.seen
set, we add it to unique_list
and also add it to the seen
set to mark it as processed.unique_list
to standard output.original_list = [1, 2, 2, 3, 4, 4, 5]
unique_list = []
seen = set()
for item in original_list:
if item not in seen:
unique_list.append(item)
seen.add(item)
print(unique_list)
[1, 2, 3, 4, 5]
In this example,
original_list
with some duplicate string elements.unique_list
to store the elements without duplicates.seen
to keep track of elements that have already been added to unique_list
.original_list
.seen
set.seen
set, we add it to unique_list
and also add it to the seen
set to mark it as processed.unique_list
to standard output.original_list = ["apple", "banana", "apple", "orange", "banana"]
unique_list = []
seen = set()
for item in original_list:
if item not in seen:
unique_list.append(item)
seen.add(item)
print(unique_list)
['apple', 'banana', 'orange']
In this tutorial, we learned How to Remove Duplicates in a List in Python language with well detailed examples.