Find Unique Elements from Tuple Using re module.

The program uses the re module in Python to extract unique elements from a given tuple. It converts the tuple to a string and uses the re.findall() method to extract all the digits from the string as strings. It then uses the map() function to convert the strings to integers and then converts the resulting list to a set to remove duplicates. Finally, it converts the set back to a tuple and prints the result

Python3




import re
 
numbers = (1, 2, 3, 4, 2, 5, 7, 2, 2, 4)
unique_numbers = tuple(map(int, re.findall(r'\d+', str(numbers))))
unique_numbers = tuple(set(unique_numbers))
print(unique_numbers)


Output

(1, 2, 3, 4, 5, 7)

Time complexity:
The time complexity of the program is O(n) where n is the number of elements in the input tuple. The re.findall() method has a time complexity of O(n) where n is the length of the string, and the set() function has a time complexity of O(n) where n is the number of elements in the input iterable.

Auxiliary Space:
The space complexity of the program is also O(n) where n is the number of elements in the input tuple. This is because the program creates a new list to store the extracted digits as strings, and then creates a new set to remove duplicates before converting back to a tuple. The space used by these data structures is proportional to the number of elements in the input tuple.

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 :

Similar Reads

By using brute force to get unique elements from tuples

In brute force, we will be using 2 for loops for checking the same values....

By iterative method to get unique elements from tuples

...

By using set data-structure to get unique elements from tuples

In this method, a loop can be used to store the unique values in a list and then converting that list into tuple....

Find Unique Elements from Tuple Using Counter() function

...

Find Unique Elements from Tuple Using re module.

As set stores unique values so we use a set to get the unique values from a tuple....

Find Unique Elements from Tuple Using Enumeration()

...