By iterative method 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.

Python3




# function for iteration and finding unique values
def unique_numbers(numbers):
    un = []
    for num in numbers:
        if num not in un:
            un.append(num)
    # to convert list into tuple using tuple() function
    unique_tuple = tuple(un)
    return unique_tuple
 
 
# print the unique tuple by extracting all the unique elements
numbers = (1, 2, 3, 4, 2, 2, 2, 1, 5, 4, 3, 4, 3)
print(unique_numbers(numbers))


Output

(1, 2, 3, 4, 5)

The time complexity of this function is O(n^2), because the “in” operator in the if statement has a time complexity of O(n) and it’s used n times in the for loop.

The space complexity is O(n), because the maximum space required by the un list 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 :

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()

...