Python: Using XOR operator find unique elements in array

Problem:- Consider an array of  integers, , where every element in  occurs exactly twice except for one unique element.Find and print the unique element.

Input :- 4 9 95 93 57 4 57 93 9 #Input array with 95 as unique element.

:- 95

Background of XOR operator ( ^ ) :-  Bit-wise operator which results zero, if XOR operator is applied between same bits otherwise gives 1.
XOR Operator operation 
We can use XOR operation to reset all bit for two numbers , if they are same.  i.e : 3 ^ 3 = 0

Sample program to print unique element using XOR :-


def lonely_integer(a):
    storage = a[0]
    for i in range(1, a.__len__()):
        storage = storage ^ a[i]
    #print (storage)
    return storage
print "Enter size of array (Input) "
n = int(raw_input().strip())
print "Enter elements separated by space "
a = map(int,raw_input().strip().split(' '))
print "Unique element is "
print lonely_integer(a)

Sample output:-
Enter size of array (Input)
Enter elements separated by space
4 9 95 93 57 4 57 93 9
Unique element is


  1. Great Article. Thank you for sharing! Really an awesome post for every one.

    IEEE Final Year projects Project Centers in Chennai are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation. For experts, it's an alternate ball game through and through. Smaller than expected IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble. Final Year Project Domains for IT It gives you tips and rules that is progressively critical to consider while choosing any final year project point.

    Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
    Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai

Previous Post Next Post