How to Get Unique Values From a List in Python?
There are several ways to get unique values from a list in Python:
- 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]
- 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]
- 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]