Extract Unique Elements from Tuple in Python

In this post, I’ll explain to you about tuples and how you can extract unique elements from tuples in Python. So let’s get started.

Python Tuples:

Before discussing tuples let me first explain with you what is the main difference between tuples and lists.

The main difference between tuples and lists is that lists are mutable while the tuples are immutable means after declaring a tuple we can’t modify it or change it while we can modify the list after it’s the declaration that’s the main difference between list and tuples.

Tuples are a built-in data type in Python that can store multiple values in it. It can also store duplicate values in it. Tuples are immutable we can’t modify them after the declaration. 

For more about Python, tuples follow this link:-https://docs.python.org/3/tutorial/datastructures.html

For accessing any particular elements of tuple we can use their index number as we use in the list. We declare tuples with the parentheses instead of using square brackets as below:-

#declaration of a tuple
fruits = ('Apple', 'Mango', 'Banana')


('Apple', 'Mango', 'Banana')

Extracting Unique Elements from a Tuple in Python

To extract the unique values from a tuple in Python we can use many methods some of which I’ll discuss here with you.

1. Using set to get the unique value-

As you already know that a set contains a unique value so here we’ll use a set to get the unique values from a tuple:-

#program to find the uique elements from the tuple using set
numbers = (1, 2, 3, 4, 3, 2, 5, 7, 7, 2, 2, 4)
unique_numbers = tuple(set(numbers))  #this will take only unique numbers from the tuple and 
#store in the another tuple unique_numbers


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

2. Using Iterations (for loop):-

We can also find the unique elements from the tuples using iterations like below it is one of the easiest ways to find the unique elements from the Python tuples:-

# Python program to extract all the unique elements from tuple using iterstions
numbers = (1, 2, 3, 4, 2, 2, 2, 1, 5, 4, 3, 4, 3)
#function for iteration and finding unique values
def unique_numbers(numbers):
    unique = []
    for number in numbers:
        if number not in unique:
    # to convert list into tuple using tuple() function
    unique_tuple = tuple(unique)
    return unique_tuple

#print the unique tuple by extracting all the unique elemnts



Also read: Printing Lists as Tabular Data in Python

Leave a Reply

Your email address will not be published. Required fields are marked *