Q:

Python program to extract unique elements in nested tuple

belongs to collection: Python Tuple Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to perform subtraction of elements ... >>
<< Python program to multiply adjacent elements of a ...