Python program to extract unique elements in nested tuple

In this program, we are given a list of tuples. We need to create a Python program to extract unique elements in a nested tuple.
Submitted by Shivang Yadav, on December 29, 2021

Extracting unique value from collections is useful in working with nested collections. Here, we will see how to extract unique elements in a nested Tuple.

Before going further with the problem, let's recap some basic topics that will help in understanding the solution.

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.

Example:

tuple = ("python", "includehelp", 43, 54.23)

Extracting unique elements in nested tuple

In this problem, we are given a list of tuples. In our program, we will be creating a tuple that will contain all the unique elements from the list of tuples.

Input:
[(4, 6, 9), (1, 5, 7), (3, 6, 7, 9)]

Output:
(4, 6, 9, 1, 5, 7, 3)

To extract all unique elements from the list of tuples, we will iterate over on the nested collection and create a unique collection. And if an element is not present in the unique collection add to it otherwise move forward.

Method 1:

One method to solve the problem is by flattering the nested collection and then converting it to a set that will remove all duplicate values and then converting the set to a tuple to get the required result. The flattering is done using from_iterable() method of itertools.

# Python program to extract unique elements
# in nested tuple

from itertools import chain

# Initializing and tuple list of tuples 
tupList = [(4, 6, 9), (1, 5, 7), (3, 6, 7, 9)]

print("The list of tuples is " + str(tupList))

# Extracting Unique elements from the tuple 
uniqueVal = tuple(set(chain.from_iterable(tupList)))

print("All unique elements of the nested Tuples are " + str(uniqueVal))

Output:

The list of tuples is [(4, 6, 9), (1, 5, 7), (3, 6, 7, 9)]
All unique elements of the nested Tuples are (1, 3, 4, 5, 6, 7, 9)

Python Tuple Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.