Sometimes, we want to remove duplicates in lists in Python.
In this article, we’ll look at how to remove duplicates in lists in Python.
How to remove duplicates in lists in Python?
To remove duplicates in lists in Python, we can convert the list to a set and then back to a list with the set
and list
functions respectively.
For instance, we write:
t = [1, 2, 3, 1, 2, 5, 6, 7, 8]
s = list(set(t))
print(s)
We call set
with t
to return a set with t
‘s elements but without the duplicates.
Then we call list
to convert the set back to a list and assign it to s
.
Therefore, s
is [1, 2, 3, 5, 6, 7, 8]
.
Conclusion
To remove duplicates in lists in Python, we can convert the list to a set and then back to a list with the set
and list
functions respectively.