Get unique values from a list in Python

PythonServer Side ProgrammingProgramming

A list in python is a number of items placed with in [] which may or may not have same data types. It can also contain duplicates. In this article we will see how to extract only the unique values from a list.

With append()

In this approach we will first create a new empty list and then keep appending elements to this new list only if it is not already present in this new list. A for loop is used along with not in condition. It checks for the existence of the incoming element and it is appended only if it is not already present.

Example

 Live Demo

def catch_unique(list_in):
   # intilize an empty list
   unq_list = []

   # Check for elements
   for x in list_in:
      # check if exists in unq_list
      if x not in unq_list:
         unq_list.append(x)
         # print list
   for x in unq_list:
      print(x)

Alist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40]
print("Unique values from the list is")
catch_unique(Alist)

Output

Running the above code gives us the following result −

Unique values from the list is
Mon
Tue
wed
40

With Set

A set only contains unique values. In this approach we convert the list to a set and then convert the set back to a list which holds all the unique elements.

Example

 Live Demo

Alist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40]
A_set = set(Alist)
New_List=list(A_set)
print("Unique values from the list is")
print(New_List)

Output

Running the above code gives us the following result −

Unique values from the list is
[40, 'Tue', 'wed', 'Mon']

Using numpy

The numpy library has a function named unique which does the straight job of taking the list as input and giving the unique elements as a new list.

Example

 Live Demo

import numpy as np

Alist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40]
print("The unique values from list is: ")
print(np.unique(Alist))

Output

Running the above code gives us the following result −

The unique values from list is:
['40' 'Mon' 'Tue' 'wed']
raja
Published on 09-Sep-2020 16:05:26
Advertisements