How to find unique numbers in an array in Python

In this tutorial, we will learn how to find unique numbers in an array in Python in cool and easy ways.

I know you are here because your stuck up with a problem to find unique elements of a list then this is the best place where you can find the best ways to solve the problem.

Find unique numbers in an array in Python

Come on lets move a head to find the awesome tricks to solve the problem

Let us consider a list of elements i.e

list_elements =[1,1,1,2,3,4,5,6,6,7,7]

 

In this list elements 1,6,7 are repeated more than once but in our output we have to print them only once

Here we can learn how to find unique numbers of the array in two ways

1.Using set keyword

2.Using conditional statements

Using set keyword

By using set function we can find the unique elements of the list because set is a collection of different elements .

The set of elements are stored in the variable unique_set

Below piece of code gives us the syntax to use set keyword.

unique_set=set(list_elements)

 

After finding the unique elements of the list we need convert the set into list to perform the other operations.

These are stored in a new list named as unique_elements

unique_elements=(list(unique_set))

 

By using for loop we can print the unique elements

for x in unique_elements:
    print(x)

 

The complete code to find the unique numbers in given below

list_elements=[1,1,1,2,3,4,5,6,6,7,7]
unique_set=set(list_elements)
unique_elements = (list(unique_set)) 
for x in unique_list: 
    print(x)

 

Output :

1
2
3
4
5
6
7

 

Using conditional statement

In this method we use conditional statement i.e if statement to find the unique numbers of the list.

First we initialize a list to store the unique elements .

unique_elements=[]

Then by using if condition we can check whether the element is present in the unique_element or not if the element is not present in unique_elements we will use append function to add the elements in unique_elements list.

If the element is already present in unique_elements then the element is not appended

for x in list_elements: 
    if x not in unique_elements: 
        unique_elements.append(x)

 

By using for loop we can print the unique elements

for x in unique_elements:
    print(x)

The complete code to find the unique numbers in given below

list_elements =[1,1,1,2,3,4,5,6,6,7,7]
unique_elements=[]
for x in list_elements: 
    if x not in unique_elements: 
        unique_elements.append(x)

for x in unique_elements:
    print(x)

 

Output:

1
2
3
4
5
6
7

Related content :

How to convert octal to hexadecimal in python

One response to “How to find unique numbers in an array in Python”

  1. Sathish Lella says:

    Good work vikas

Leave a Reply

Your email address will not be published. Required fields are marked *