Skip to content

Python Find Unique values in the List

  • by

Finding a unique value in the Python list or removing a duplicate can be done by doing a Traversal of a list, Using a set, or import a numpy.unique.

3 ways to get Unique value from a list

  • List Traversing
  • Using set
  • Numpy.unique

Let’s see the Example of Python find unique values in the list

Let’s see all method examples code:

1. Traversal of list

In the example, we will traverse every element in the list and store unique values in the list. Meanwhile, on adding a new value to the unique_list make sure this value does not exist in the list.

This can be done using for loop and if statement.

# function to get unique values
def unique(list_value):
    # empty list to store unique values
    unique_list = []

    # traverse for all elements
    for x in list_value:
        # check if exists in unique_list or not
        if x not in unique_list:
            unique_list.append(x)
            # print list
    for x in unique_list:
        print(x)
        
# List with duplicates
list1 = [3, 1, 1, 1, 9, 3, 10]
print("\nThe unique values from the list are")
unique(list1)

Output:

The unique values from the list are
3
1
9
10

2. Using set

A set is containing only unique values. So if you store the value of the list into the set, then you will get only a unique value.

After inserting all the values in the set convert this set to a list and then print it.

# function to get unique values
def unique(list_value):
    # insert the list to the set
    list_set = set(list_value)
    # convert the set to the list
    unique_list = (list(list_set))
    for x in unique_list:
        print(x)


# List with duplicates
list1 = [2, 1, 1, 1, 4, 3]
print("\nThe unique values of List")
unique(list1)

Output:

The unique values of List
1
2
3
4

3. Using Numpy.unique Method

Use NumPy.unique() function to get the unique values from the list. You have to import NumPy to use the unique() function. You might have to install a Numpy module.

See the below screenshot.

python find unique values in list

After installation Numpy module you can use it.

# function to get unique values
# using numpy.unique
import numpy as np

# function to get unique values
def unique(list_value):
    x = np.array(list_value)
    print(np.unique(x))


# List with duplicates
list1 = [2, 2, 3, 1, 4, 2]
print("\nThe unique List")
unique(list1)

Output:

The unique List
[1 2 3 4]

Do comment if you have any doubts and suggestions on this tutorial. If you have any other way to do it, please share the example in the comment section.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Python 3.7
All Python Programs are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

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