How to Get Unique Values From a List in Python?

python

There are several ways to get unique values from a list in Python:

  1. Using the set() Function: The set() function converts a list to a set, which automatically removes any duplicate values.

Example:

my_list = [1, 2, 3, 2, 4, 5, 3, 6, 4, 7]
unique_list = list(set(my_list))
print(unique_list)

Output: [1, 2, 3, 4, 5, 6, 7]

  1. Using a For Loop: We can iterate over each element in the list and add it to a new list if it is not already there.

Example:

my_list = [1, 2, 3, 2, 4, 5, 3, 6, 4, 7]
unique_list = []
for x in my_list:
    if x not in unique_list:
        unique_list.append(x)
print(unique_list)

Output: [1, 2, 3, 4, 5, 6, 7]

  1. Using the Numpy library: We can use the np.unique() function from the NumPy library to find the unique values in a list.

Example:

import numpy as np

my_list = [1, 2, 3, 2, 4, 5, 3, 6, 4, 7]
unique_list = np.unique(my_list)
print(unique_list)

Output: [1 2 3 4 5 6 7]

Latest Questions

python How to Fix ""zsh: command not found: python" Error on MacOS X? python How to Fix "xlrd.biffh.XLRDError: Excel xlsx file; not supported" Error in Pandas? python How to Remove All Whitespace From a Python String?