Skip to content
Related Articles

Related Articles

Python | How to get unique elements in nested tuple

Improve Article
Save Article
  • Last Updated : 21 Aug, 2022
Improve Article
Save Article

Sometimes, while working with tuples, we can have a problem in which we have nested tuples and we need to extract elements that occur singly, i.e are elementary. This kind of problem can have applications in many domains. Let’s discuss certain ways in which this problem can be solved. 

Method #1: Using nested loop + set() 

The above 2 functionalities can be used to solve this particular problem. In this, we iterate each nested tuple and add to the set if the element has occurred for the first time and check for each element before adding. 

Python3




# Python3 code to demonstrate working of
# Unique elements in nested tuple
# Using nested loop + set()
 
# initialize list
test_list = [(3, 4, 5), (4, 5, 7), (1, 4)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Unique elements in nested tuple
# Using nested loop + set()
res = []
temp = set()
for inner in test_list:
        for ele in inner:
            if not ele in temp:
                temp.add(ele)
                res.append(ele)
 
# printing result
print("Unique elements in nested tuples are : " + str(res))

Output

The original list : [(3, 4, 5), (4, 5, 7), (1, 4)]
Unique elements in nested tuples are : [3, 4, 5, 7, 1]

Method #2 : Using set() + from_iterable() 

The combo of the above functionalities can be used to solve this. This is done is 2 steps, first, we flatten the nested list and then find distinct using set() method. 

Python3




# Python3 code to demonstrate working of
# Unique elements in nested tuple
# Using from_iterable() + set()
from itertools import chain
 
# initialize list
test_list = [(3, 4, 5), (4, 5, 7), (1, 4)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Unique elements in nested tuple
# Using from_iterable() + set()
res = list(set(chain.from_iterable(test_list)))
 
# printing result
print("Unique elements in nested tuples are : " + str(res))

Output

The original list : [(3, 4, 5), (4, 5, 7), (1, 4)]
Unique elements in nested tuples are : [1, 3, 4, 5, 7]

Method #3 : Using list(),extend(),set()

Python3




# Python3 code to demonstrate working of
# Unique elements in nested tuple
 
# initialize list
test_list = [(3, 4, 5), (4, 5, 7), (1, 4)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Unique elements in nested tuple
x=[]
for i in test_list:
    i=list(i)
    x.extend(i)
res=list(set(x))
# printing result
print("Unique elements in nested tuples are : " + str(res))

Output

The original list : [(3, 4, 5), (4, 5, 7), (1, 4)]
Unique elements in nested tuples are : [1, 3, 4, 5, 7]

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!