Drop Duplicates From An Array In Python

So, you need to drop duplicates from an array in Python. Maybe you’re iterating through this array and calling an api and need to cut down on the super expensive networking? Regardless, it’s fairly straight forward.

My Setup

Python 3.x
macOS

The Solution

# Defining the problematic array
x = [1,2,3,4,4,4,4,4]
# Removing duplicates
y = list(set(x))
print(y)
[1,2,3,4]

We use set() to drop duplicates from an array in Python. A set is an unordered collection of unique elements. So to become a set() duplicates need to be removed. We then change the list of numbers back into an array using the list() function. Need to drop duplicates from a DataFrame instead? Check out this article for some help. Happy coding!

Here’s A Sandbox So You can Drop Duplicates from an Array in Python Yourself

Leave a Comment