Write a Python program to get unique elements in nested tuple


This program is used to extract unique elements from a list of nested tuples.

  • The original list, val, is defined and contains 5 nested tuples.
  • The empty list res and set s are created.
  • The program iterates over each tuple in the list val.
  • For each tuple, the program iterates over its elements and checks if the element is in the set s.
  • If the element is not in the set, it is added to the set s and appended to the list res.
  • After all tuples have been processed, the list res contains all unique elements from the nested tuples in val.
  • The final result is printed on the screen with the message "Unique Element in Nested Tuples".

Note that sets are used in this program to keep track of unique elements. Since sets only allow unique values, it ensures that each element is only added to the res list once, even if it appears multiple times in the nested tuples.

Source Code

val = [(1, 3, 5), (4, 5, 7), (1, 2, 6), (10, 9), (10,)]
 
print("The original ljst : " ,val)
res = []
s = set()
for i in val:
	for j in i:
		if not j in s:
			s.add(j)
			res.append(j)
 
print("Unique Element in Nested Tuples : " ,res)

Output

The original ljst :  [(1, 3, 5), (4, 5, 7), (1, 2, 6), (10, 9), (10,)]
Unique Element in Nested Tuples :  [1, 3, 5, 4, 7, 2, 6, 10, 9]


Example Programs