Get unique values from a list in python
There are several methods to get unique elements from a list. Let’s discuss some of them in detail.
- Using append()
- Using set()
- Using List Comprehension
- Using numpy
1.Using a loop with append():
In this method, we simply traverse the given list named original_list and append the first occurrence of the element to a new list named unique_list, and ignore all the rest of the occurrences of that particular element. This ensures the duplicates aren’t repeated.
original_list= [1,3,5,7,1,3,5,7,9,11] print ("Original list is : " + str(original_list)) unique_list= for i in original_list: if i not in unique_list : unique_list.append(i) print ("Unique Elements List : " + str(unique_list))
2. Using List Comprehension:
This method works much similar to the above method but it’s a one-liner code and a shorter version of the above. We use the keywords ‘in’ and ‘not’ in keywords to know the existence of an element in the original list and the unique list to ensure no duplicates are present.
list_1= [1,3,5,7,1,3,5,7,9,11] print ("Original list is : " + str(list)) unique_list= [unique_list.append(x) for x in list if x not in unique_list] print ("Unique Elements List : " + str(unique_list))
3. Using set():
A set is a data structure that is both unordered and unindexed. They store collections of unique items separated by commas enclosed within parentheses. Sets won’t store duplicate values, unlike lists.
As we know, sets cannot store duplicate items, we’ll convert our list to a set to remove the duplicates and then convert it back to a list using list().
original_list= [1,3,5,7,1,3,5,7,9,11] print ("Original list is : " + str(original_list)) unique_list= list (set(original_list)) print ("Unique Elements List : " + str(unique_list))
4. Using numpy:
The numpy library has a function named unique() which takes the list as input and returns a new list with the unique elements.
import numpy as np original_list= [1,3,5,7,1,3,5,7,9,11] print(np.unique(original_list))