Categories
Python Answers

How to remove duplicates in lists in Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *