Built with Tutify.io

    AIStudyLabs

    Get Unique Values From a List in Python

    Get Unique Values From a List in Python

    How to get unique values from a list in Python? To get the unique values from a list, you can use the set() function. The set() function returns a collection of unique elements. Besides this, you can get unique values from a list in Python by using many ways, for example, by using the reduce(), collections.Counter(), append(), numpy.unique(), Pandas, and Operator.countOf() functions.

    In this article, I will explain get unique values from a list by using all these methods with examples.

    <a id="h-1-quick-examples-of-getting-unique-values-from-list"></a>

    1. Quick Examples of Getting Unique Values From List

    If you are in a hurry, below are some quick examples of how to get unique values from a list.

    
    # Quick examples to get unique values from list
    
    # Initialize lists
    lists = [5, 4, 2, 3, 2, 3, 4, 2, 5, 4]
    
    # Example 1: Using set() function
    list_set = set(lists)
    result = list(list_set)Get unique values from a list 
    
    # Example 2: Using reduce() function
    def unique(lists):
           unique_values = reduce(lambda x, y: x + [y] if y not in x else x, lists, [])
        print(unique_values)
    unique(lists)
    
    # Example 3: Using collections.Counter()
    def unique(lists):
           print(*Counter(lists))
    unique(lists)
    
    # Example 4: Get unique values from a list 
    # Using append() function
    empty_list = []
    for item in lists: 
        if item not in empty_list: 
            empty_list.append(item) 
    print("Unique values of the list:\n")    
    for item in empty_list: 
        print(item)
    
    # Example 5: Initialize the list
    # Get unique values from a list 
    # Using numpy.unique() function
    print("Unique values of list:\n", np.unique(np.array(lists)))   
    
    # Example 6: Using pandas
    def unique(lists):
        unique_list = pd.Series(lists).drop_duplicates().tolist()
        for x in unique_list:
            print(x)
    unique(lists)
    
    # Example 7 : Using Operator.countOf() method
    def unique(lists):
         unique_list = []
        for x in lists:
               if op.countOf(unique_list, x) == 0:
                unique_list.append(x)
            for x in unique_list:
            print(x)
    unique(lists)
    

    <a id="h-2-get-unique-values-from-a-list-using-set-property"></a>

    2. Get Unique Values from a List Using set() Property

    The set() is a built-in function that can take the list as an argument and returns a Python Set object with unique elements. This function removes all duplicate elements of list automatically and kept only the unique elements. Convert the set to a list by using list() to get the unique elements in the list.

    For example, the lists variable contains duplicate values, by passing it to the set() function, it will return a new set set1 that contains only the unique elements from lists.

    
    # Initialize the list
    lists = [5, 4, 2, 3, 2, 3, 4, 2, 5, 4]
    print("Given list:", lists)
    
    # Get unique values from a list 
    # Using set() method
    set1 = set(lists)
    
    # Convert set to list
    result = list(set1)
    print("Unique value list:", result)
    

    Yields below output.

    <a id="h-3-get-unique-values-from-a-list-using-reduce-function"></a>

    3. Get Unique Values from a List Using reduce() Function

    Alternatively, you can also use the reduce() function from the functools module along with a lambda function to get the unique values from a list. The reduce() function repeatedly applies the lambda function to the elements of the list and returns a single value.

    Let's define the unique() function and pass the given list as an argument and get the unique values using reduce() along with the lambda function.

    
    # Import functools
    from functools import reduce
    
    # Get unique values from a list 
    # Using reduce() function
    lists = [0, 1, 2, 2, 3, 3, 4, 5, 5, 5]
    def unique(lists):
        unique_values = reduce(lambda x, y: x + [y] if y not in x else x, lists, [])
        print("Unique values list:", unique_values)
    unique(lists)
    

    In this example, the lambda function checks if each element y in the list is already present in the accumulator x (which starts as an empty list []). If y is not already in x, it appends y to x using the + operator. If y is already in x, it simply returns x unchanged. The reduce() function then applies this lambda function to all the elements of the list, resulting in a list of unique values.

    Yields below output.

    <a id="h-4-get-unique-values-from-a-list-using-collections-counter"></a>

    4. Get Unique Values from a List Using collections.Counter()

    You can also use the collections.Counter() function to get the unique values from a list. The Counter(lists) function returns a dictionary containing the count of each element in the list.

    The * symbol is used to print the keys of the dictionary (i.e., the unique values) directly as separate arguments to the print() function, instead of printing the dictionary itself.

    
    # Import collections module
    from collections import Counter
    
    # Get unique values from a list 
    # Using collections.Counter()
    lists = [0, 2, 4, 6, 2, 4, 8]
    
    def unique(lists):
        # Print directly by using * symbol
        print(*Counter(lists))
    unique(lists)
    

    Yields below output.

    
    # Output:  
    0 2 4 6 8
    

    <a id="h-5-get-unique-values-using-python-list-append"></a>

    5. Get Unique Values Using Python list.append()

    Alternatively, you can use the append() function along with for loop to get the unique values from a list. First initializes an empty list and iterate the given list of values using for loop. For every iteration, the obtained item will check if it is present in the empty list or not. If it is not it will add to the empty list using the append() function. Finally, iterate an empty list that contains unique values using for loop and print them.

    
    # Initialize the list
    lists = [10, 20, 10, 30, 40, 40, 50, 30]
    
    # Get unique values from a list 
    # Using append() function
    empty_list = []
    for item in lists: 
        if item not in empty_list: 
            empty_list.append(item) 
    
    print("Unique values of the list:\n")    
    for item in empty_list: 
        print(item)
    

    Yields below output.

    
    # Output:
    Unique values of the list:
    10
    20
    30
    40
    50
    

    <a id="h-6-using-numpy-unique-function"></a>

    6. Using numpy.unique() Function

    You can also use the unique() function of numpy module in Python to get the unique values from a list. The numpy.unique() function takes an array as its parameter and returns an array containing only the unique values of the input array.

    Before going to use numpy.unique() function we need to convert the list to a NumPy array using the np.array() function. Let's apply unique() function over the array and get the unique values from it.

    
    # Import the numpy module
    import numpy as np
    
    # Initialize the list
    lists = [2, 4, 2, 3, 4, 1, 5]
    
    # Convert list to NumPy array
    arr = np.array(lists)
    
    # Get unique values from a list 
    # Using numpy.unique() function
    print("Unique values of list:\n", np.unique(arr))
    

    Yields below output.

    
    # Output:
    Unique values of the list:
    [1 2 3 4 5]
    

    <a id="h-7-get-unique-values-from-a-list-using-pandas"></a>

    7. Get Unique Values from a List Using Pandas

    You can use the pandas module to get unique values from a list, for example, the unique() function takes a list as an argument, converts it to a pandas Series object, and drops the duplicate values using the drop_duplicates() method, and then converts the resulting Series object back to a list using the tolist() method. The unique values are then printed using the print() function in a loop.

    
    # Import pandas
    import pandas as pd
    
    # Initialize the list
    lists = [1, 2, 3, 2, 3, 4, 1, 5]
     
    # Get unique values from a list 
    # Using pandas
    def unique(lists):
        unique_list = pd.Series(lists).drop_duplicates().tolist()
        for x in unique_list:
            print(x)
    unique(lists)
    

    Yields below output.

    
    # Output:
     1
     2
     3
     4
     5
    

    <a id="h-8-using-operator-countof-method"></a>

    8. Using Operator.countOf() Method

    Finally, you can also use the operator.countOf() method to get unique values. The input list is defined as lists with some elements. The function unique() takes this list as an argument. Inside the function, an empty list unique_list is initialized to store the unique elements. The for loop iterates over each element in the input list lists.

    The op.countOf() method checks if the current element x already exists in the unique_list or not. If the count of x in unique_list is zero, then it means x is a unique element and is appended to unique_list. Finally, the function prints all the unique elements in the unique_list using another for loop.

    
    # Import module
    import operator as op
    
    # Using Operator.countOf() method
    lists = [1, 2, 3, 2, 3, 4, 1, 5] 
     
    def unique(lists):
        # initialize a null list
        unique_list = []
    
        for x in lists:
            # check if exists in unique_list or not
            if op.countOf(unique_list, x) == 0:
                unique_list.append(x)
            for x in unique_list:
            print(x)
    unique(lists)
    

    Yields the same output as above.

    <a id="h-9-conclusion"></a>

    9. Conclusion

    In this article, I have explained how to get unique values from a list in Python by using the set(), reduce(), collections.Counter(), append(), numpy.unique(), Pandas, and Operator.countOf() functions with examples. Depending on your need you can use any of these methods.

    Happy Learning !!

    <a id="h-related-articles"></a>

    Related articles