
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find which element occurs exactly once in Python
In Python, datastructures such as string, list etc., may contain duplicates of a value. In few scenarios, we may need to find which element appears only once while all others elements appear multiple times. Let's go through different methods to find which element occurs exactly once in Python.
Using Bitwise XOR
The XOR is abbrivated as Exclusive OR is a bitwise operator which returns 1 if the corresponding bits of two operands are different otherwise, it returns 0 if they are same. In Python, we can use the ^ between two operands to perform Exclusive OR operation.
Example
Following is the example, in which we are using the ^ to perform XOR operation on the given input elements to get the unique element from the input -
def find_unique_element(arr): result = 0 for num in arr: result ^= num return result # Sample input list numbers = [7, 3, 5, 4, 5, 3, 4] print("Element that occurs exactly once:", find_unique_element(numbers))
Following is the output of the above example -
Element that occurs exactly once: 7
Using collections.Counter
The Counter is a subclass of the collections module in Python which is used to count the frequency of elements in a container such as list, tuple or string. It returns a dictionary where elements are stored as dictionary keys and their counts as dictionary values.
Example
In this example, we are using the Counter class to count the number of occurrences of elements in the input string and retrieve only those elements whose count is exactly 1 i.e., appeared only once -
from collections import Counter def find_elements_occurring_once(arr): freq = Counter(arr) return [num for num, count in freq.items() if count == 1] # Sample input list numbers = "1 3 4 7 b 7 3 4 b" print("Elements that occur exactly once:", find_elements_occurring_once(numbers))
Here is the output of the above example -
Elements that occur exactly once: ['1']