Python | How to get unique elements in a nested tuple



Method # 1: Using a nested loop + set()
The above 2 functionality can be used to solve this particular problem. In this, we iterate over each nested tuple and add to install if the element is encountered for the first time, and validate each element before adding.

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 ()
A combination of the above functions can be used to solve this problem. This is done in 2 steps, first we flatten the nested list and then find the differences with set () .

# Python3 code to demonstrate how it works
# Unique elements in a nested tuple
# Using a nested loop + set ()

 
# initialize the list

test_list = [( 3 , 4 , 5 ), ( 4 , 5 , 7 ), ( 1 , 4 )]

 
# print original list

print ( "The original list:" + str (test_list))

 
# Unique elements in a 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)

 
# print result

print ( "Unique elements in nested tuples are: " + str (res))

# Python3 code to demonstrate how it works
# Unique elements in a nested tuple
# Using from_iterable () + set ()

from itertools import chain

 
# initialize the list

test_list = [( 3 , 4 , 5 ), ( 4 , 5 , 7 ), ( 1 , 4 )]

 
# print original list

print ( "The original list:" + str (test_list))

  
# Unique elements in a nested tuple
# Using from_iterable () + set ()

res = list ( set (chain.from_iterable (test_list)))

 
# print 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]