The Wayback Machine - https://web.archive.org/web/20240604211811/https://www.geeksforgeeks.org/python-get-unique-values-list/
Open In App

Python | Get unique values from a list

Last Updated : 17 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will explore various techniques and strategies for efficiently extracting distinct elements from a given list. By delving into methods ranging from traditional loops to modern Pythonic approaches with Python.

Input : [1,2, 1, 1, 3, 4, 3, 3, 5 ]
Output : [1, 2, 3, 4, 5]  
Explaination: The output only contains the unique element from the input list.

Get unique values from a list

Below are the topics that we will cover in this article:

Get Unique Values from a List by Traversal of the List

Using traversal, we can traverse for every element in the list and check if the element is in the unique_list already if it is not over there, then we can append it to the unique_list. This is done using one for loop and another if statement which checks if the value is in the unique list or not which is equivalent to another for a loop.  

Python3




# function to get unique values
def unique(list1):
 
    # initialize a null list
    unique_list = []
 
    # traverse for all elements
    for x in list1:
        # 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,
 
 
# driver code
list1 = [10, 20, 10, 30, 40, 40]
print("the unique values from 1st list is")
unique(list1)
 
 
list2 = [1, 2, 1, 1, 3, 4, 3, 3, 5]
print("\nthe unique values from 2nd list is")
unique(list2)


Output

the unique values from 1st list is
10 20 30 40 
the unique values from 2nd list is
1 2 3 4 5




Time Complexity: O(n*n)
Auxiliary Space: O(n)

Get Unique Values from a List Using Set Method

Using set() property of Python, we can easily check for the unique values. Insert the values of the list in a set. Set only stores a value once even if it is inserted more than once. After inserting all the values in the set by list_set=set(list1), convert this set to a list to print it. 

Python3




def unique(list1):
 
    # insert the list to the set
    list_set = set(list1)
    # convert the set to the list
    unique_list = (list(list_set))
    for x in unique_list:
        print x,
 
 
# driver code
list1 = [10, 20, 10, 30, 40, 40]
print("the unique values from 1st list is")
unique(list1)
 
 
list2 = [1, 2, 1, 1, 3, 4, 3, 3, 5]
print("\nthe unique values from 2nd list is")
unique(list2)


Output

the unique values from 1st list is
40 10 20 30 
the unique values from 2nd list is
1 2 3 4 5




Time complexity: O(n), where n is the length of a list.
Auxiliary Space: O(n), where n is the length of a list.

Get Unique Values From a List in Python Using reduce() function

Using Python import reduce() from functools and iterate over all element and checks if the element is a duplicate or unique value. Below is the implementation of the above approach.

Python3




from functools import reduce
 
def unique(list1):
 
    # Print directly by using * symbol
    ans = reduce(lambda re, x: re+[x] if x not in re else re, list1, [])
    print(ans)
 
 
# driver code
list1 = [10, 20, 10, 30, 40, 40]
print("the unique values from 1st list is")
unique(list1)
 
 
list2 = [1, 2, 1, 1, 3, 4, 3, 3, 5]
print("\nthe unique values from 2nd list is")
unique(list2)


Output

the unique values from 1st list is
[10, 20, 30, 40]

the unique values from 2nd list is
[1, 2, 3, 4, 5]



Get Unique Values From a List in Python Using Operator.countOf() method

The ‘unique’ function initializes an empty ‘unique_list’, then iterates through ‘list1’. For each element ‘x’, it employs ‘op.countOf()‘ to check if ‘x’ is present in ‘unique_list’. If not found (count is 0), ‘x’ is appended to ‘unique_list’. The final unique values are printed using a loop. The driver code demonstrates this process for two lists, ‘list1’ and ‘list2’, showcasing the extraction of distinct elements from each list while maintaining their original order.

Python3




import operator as op
# function to get unique values
 
 
def unique(list1):
 
    # initialize a null list
    unique_list = []
 
    # traverse for all elements
    for x in list1:
        # check if exists in unique_list or not
        if op.countOf(unique_list, x) == 0:
            unique_list.append(x)
    # print list
    for x in unique_list:
        print(x)
 
# driver code
list1 = [10, 20, 10, 30, 40, 40]
print("the unique values from 1st list is")
unique(list1)
 
list2 = [1, 2, 1, 1, 3, 4, 3, 3, 5]
print("\nthe unique values from 2nd list is")
unique(list2)


Output

the unique values from 1st list is
10
20
30
40

the unique values from 2nd list is
1
2
3
4
5




Time Complexity:O(N)
Auxiliary Space: O(N)

Get Unique Values From a List in Python Using pandas module

The ‘unique’ function utilizes Pandas to create a Series from ‘list1’, then employs ‘drop_duplicates()’ to eliminate duplicates and obtain a list of unique values. Subsequently, it iterates through the unique list and prints each element. The driver code demonstrates the process for two lists, ‘list1’ and ‘list2’, providing distinct values for each list.

Python3




import pandas as pd
 
# function to get unique values
def unique(list1):
    unique_list = pd.Series(list1).drop_duplicates().tolist()
    for x in unique_list:
        print(x)
 
# driver code
list1 = [10, 20, 10, 30, 40, 40]
print("the unique values from 1st list is")
unique(list1)
 
list2 = [1, 2, 1, 1, 3, 4, 3, 3, 5]
print("\nthe unique values from 2nd list is")
unique(list2)
#This code is contributed by Vinay Pinjala.


Output:

the unique values from 1st list is
10
20
30
40
the unique values from 2nd list is
1
2
3
4
5

Time Complexity:O(N)
Auxiliary Space: O(N)

Get Unique Values From a List Using numpy.unique

Using Python’s import numpy, the unique elements in the array are also obtained. In the first step convert the list to x=numpy.array(list) and then use numpy.unique(x) function to get the unique values from the list. numpy.unique() returns only the unique values in the list. 

Python3




# using numpy.unique
import numpy as np
 
def unique(list1):
    x = np.array(list1)
    print(np.unique(x))
 
 
# driver code
list1 = [10, 20, 10, 30, 40, 40]
print("the unique values from 1st list is")
unique(list1)
 
 
list2 = [1, 2, 1, 1, 3, 4, 3, 3, 5]
print("\nthe unique values from 2nd list is")
unique(list2)


Output: 

the unique values from 1st list is
[10 20 30 40]
the unique values from 2nd list is
[1 2 3 4 5]

Time complexity: O(nlogn) due to the use of the sorting algorithm used by the numpy.unique() function. 
Auxiliary space: O(n) because numpy.unique() function creates a copy of the input array and then sorts it before returning the unique elements. 

Get Unique Values From a List in Python Using collections.Counter()

Using Python to import Counter() from collections print all the keys of Counter elements or we print directly by using the “*” symbol. Below is the implementation of the above approach.

Python3




from collections import Counter
 
# Function to get unique values
 
 
def unique(list1):
 
    # Print directly by using * symbol
    print(*Counter(list1))
 
 
# driver code
list1 = [10, 20, 10, 30, 40, 40]
print("the unique values from 1st list is")
unique(list1)
 
 
list2 = [1, 2, 1, 1, 3, 4, 3, 3, 5]
print("\nthe unique values from 2nd list is")
unique(list2)


Output

the unique values from 1st list is
10 20 30 40

the unique values from 2nd list is
1 2 3 4 5




Time Complexity: O(n), where n is the number of elements in the input list.
Auxiliary Space : O(n)

Get Unique Values From a List Using dict.fromkeys()

Using the fromkeys() method of dictionary data structure we can fetch the unique elements.Firstly we need to define a list that consists of duplicate elements.Then we need to use a variable in which we will store the result after using the fromkeys() method.We need to convert that result into a list, as the fromkeys() method is part of the dictionary so by default it returns a dictionary with all the unique keys and None as their values.

Python3




# defining a list which consists duplicate values
list1 = [10, 20, 10, 30, 40, 40]
 
list2 = [1, 2, 1, 1, 3, 4, 3, 3, 5]
 
# storing the result of the fromkeys()
# operation and converting it into list
unique_list_1 = list(dict.fromkeys(list1))
 
unique_list_2 = list(dict.fromkeys(list2))
 
# Printing the final result
print(unique_list_1,unique_list_2,sep="\n")


Output

[10, 20, 30, 40]
[1, 2, 3, 4, 5]



Time Complexity – O(n)
Space Complexity – O(n)



Similar Reads

Python | Get Unique values from list of dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to find the unique values over all the dictionaries in a list. This kind of utility can occur in case while working with similar data and we wish to extract the unique ones. Let's discuss certain ways in which this task can be performed. Method #1 : Using set(
4 min read
Python - Extract Unique values dictionary values
Sometimes, while working with data, we can have problem in which we need to perform the extraction of only unique values from dictionary values list. This can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed. Extract Unique values dictionary values Using sorted() + set comprehen
7 min read
Get unique values from a column in Pandas DataFrame
The unique() function removes all duplicate values on a column and returns a single value for multiple same values. In this article, we will discuss how we can get unique values from a column in Pandas DataFrame. Creating a Pandas Dataframe with Duplicate ElementsCreate a sample Pandas dataframe with a dictionary of lists, say columns names are A,
4 min read
Counting number of unique values in a Python list
Let us see how to count the number of unique values in a Python list. Examples : Input : 10 20 10 30 40 40Output : 2Explanation : Only 2 elements, 20 and 30 are unique in the list. Input : 'geeks' 'for' 'geeks'Output : 1 Approach 1: Traversing the list and counting the frequency of each element using a dictionary, finally counting the elements for
6 min read
Python | Get unique tuples from list
Sometimes, while working with Python list, we can come across a problem in which we require to find the unique occurrences of list. Having elementary data types is easy to handle, but sometime, we might have complex data types and the problem becomes new in that cases. Let's discuss certain ways in which tuples are handled for this problem. Method
3 min read
Python - Get a sorted list of random integers with unique elements
Given lower and upper limits, generate a sorted list of random numbers with unique elements, starting from start to end. Examples: Input: num = 10, start = 100, end = 200 Output: [102, 118, 124, 131, 140, 148, 161, 166, 176, 180] Input: num = 5, start = 1, end = 100 Output: [37, 49, 64, 84, 95] To generate random numbers in Python, randint() functi
2 min read
Python Program to get all unique keys from a List of Dictionaries
Given a list arr[] consisting of N dictionaries, the task is to find the sum of unique keys from the given list of the dictionary. Examples: Input: arr = [{'my': 1, 'name': 2}, {'is': 1, 'my': 3}, {'ria': 2}]Output: ['ria', 'my', 'is', 'name']Explanation: The set of unique keys are {"ria", "my", "Is", "name"}. Input: arr = [{'X': 100, 'Y': 2}, {'Z'
4 min read
How to count unique values inside a list
There are several methods for finding or counting unique items inside a list in Python. Here we'll discuss 3 methods. Method 1: The first method is the brute force approach. This method is not very much efficient as it takes more time and space. In this method, we take an empty array and a count variable(set to be zero). We traverse from the start
3 min read
Python - Assign values to Values List
Given 2 dictionaries, assign values to value list elements mapping from dictionary 2. Input : test_dict = {'Gfg' : [3, 6], 'best' :[9]}, look_dict = {3 : [1, 5], 6 : "Best", 9 : 12} Output : {'Gfg': {3: [1, 5], 6: 'Best'}, 'best': {9: 12}} Explanation : 3 is replaced by key 3 and value [1, 5] and so on. Input : test_dict = {'Gfg' : [3, 6]}, look_di
6 min read
Python | Unique values in Matrix
Sometimes we need to find the unique values in a list, which is comparatively easy and has been discussed earlier. But we can also get a matrix as input i.e a list of lists, and finding unique in them are discussed in this article. Let's see certain ways in which this can be achieved. Method #1: Using set() + list comprehension The set function can
9 min read
Practice Tags :