Find Unique Elements from Tuple Using Counter() function
Python3
from collections import Counter # To find the unique elements from the tuple using the counter def unique_numbers(numbers): # this will take only unique numbers from the tuple return tuple (Counter(numbers).keys()) numbers = ( 1 , 2 , 3 , 4 , 2 , 5 , 7 , 2 , 2 , 4 ) print (unique_numbers(numbers)) |
Output
(1, 2, 3, 4, 5, 7)
The time complexity of this function is O(n), because the Counter() function from the collections library has a time complexity of O(n) to count the occurrences of elements in an iterable object.
The space complexity is also O(n), because the maximum space required by the Counter object is n (when all elements in the input numbers are unique).
Find Unique Elements from Tuple in Python
Tuples are immutable built-in data type in Python that can store multiple values in it. Extracting Unique Elements from a Tuple in Python can be done through two different approaches.
Examples:
Input: (1, 2, 13, 4, 3, 12, 5, 7, 7, 2, 2, 4)
Output: (1, 2, 3,4,5,12,13)
Input: ('Apple', 'Mango', 'Banana', 'Mango', 'Apple')
Output: ('Apple', 'Mango', 'Banana')
Let’s start with the different methods :