Open In App

Python | How to get unique elements in nested tuple

Last Updated : 10 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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]

Time Complexity: O(n^2) where n is the total number of elements in the nested tuples. This is because we are using a nested loop to iterate through each inner tuple and then through each element within the inner tuple.
Auxiliary Space: O(n) where n is the total number of elements in the nested tuples. This is because we are using a set to store the unique elements, which takes O(n) space.

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]

Time complexity: O(n), where n is the total number of elements in all the tuples in the input list.
Auxiliary space: O(n), where n is the total number of elements in all the tuples in the input list. 

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]

Method #4 : Using Counter() function

Python3




# Python3 code to demonstrate working of
# Unique elements in nested tuple
from collections import Counter
# 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:
    x.extend(list(i))
freq = Counter(x)
res = list(freq.keys())
res.sort()
# 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 #5:Using Operator.countOf() method

Python3




# Python3 code to demonstrate working of
# Unique elements in nested tuple
 
import operator as op
# 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 op.countOf(temp,ele)==0:
                temp.add(ele)
                res.append(ele)
res.sort()
# 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]

Time Complexity: O(N)
Auxiliary Space: O(N*N)

Method #6: Using a list comprehension and set conversion.

  • Initialize a list of tuples test_list containing three nested tuples with integer elements.
  • Print the original list test_list using the print() function with a string concatenated with the list.
  • Create a list comprehension using nested for loops to iterate over each element inner in test_list and then each element x in inner. The resulting list is flattened from the nested tuples into a 1D list.
  • Convert the resulting list into a set using set(), which removes any duplicates in the list.
  • Sort the resulting set using sorted() to order the unique elements.
  • Assign the resulting list to a variable res.
  • Print the unique elements in nested tuples by concatenating a string with the variable res converted into a string using str().

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
# Using list comprehension and set conversion
res = sorted(set([x for inner in test_list for x in inner]))
 
# 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]

Time complexity: O(n), where n is the total number of elements in the nested tuples, as it involves iterating over each element once using itertools.chain. 
Auxiliary space: O(n), as we are creating a list to store the unique elements, and the size of the list can be at most n, where n is the total number of elements in the nested tuples.

Method #7: Using numpy.unique() function

Step-by-step approach:

  • Import the numpy module.
  • Initialize the list of tuples.
  • Use numpy.concatenate() to flatten the nested tuples into a single array.
  • Use numpy.unique() to get unique elements in the flattened array.
  • Convert the result into a list and sort it.
  • Print the sorted list of unique elements.

Python3




# Python3 code to demonstrate working of
# Unique elements in nested tuple
 
# import numpy module
import numpy as np
 
# 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 numpy.unique() function
res = np.unique(np.concatenate(test_list)).tolist()
 
# 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]

Time complexity: O(NlogN), where N is the total number of elements in all tuples. 
Auxiliary space: O(N), where N is the total number of elements in all tuples. 



Similar Reads

Python - Elements Frequency in Mixed Nested Tuple
Sometimes, while working with Python data, we can have a problem in which we have data in the form of nested and non-nested forms inside a single tuple, and we wish to count the element frequency in them. This kind of problem can come in domains such as web development and Data Science. Let's discuss certain ways in which this task can be performed
8 min read
Python - Extract Even elements in Nested Mixed Tuple
Sometimes, while working with Python tuples, we can have a problem in which we need to get all the even elements from the tuple. The tuples can be nested or mixed. This kind of problem can occur in data domains. Let's discuss certain ways in which this task can be performed. Input : test_tuple = (5, (7, 6, (2, (4, )))) Output : ((6, (2, (4, ))), )
4 min read
Python - Raise elements of tuple as power to another tuple
Sometimes, while working with records, we can have a problem in which we may need to perform exponentiation, i.e power of tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed. Method #1: Using zip() + generator expression The combination of above functions can be used to perform this
8 min read
Find Unique Elements from Tuple in Python
Tuples are immutable built-in data type in Python that can store multiple values in it. Extracting Unique Elements from a Tuple in Python can be done through two different approaches. Examples: Input: (1, 2, 13, 4, 3, 12, 5, 7, 7, 2, 2, 4)Output: (1, 2, 3,4,5,12,13)Input: ('Apple', 'Mango', 'Banana', 'Mango', 'Apple')Output: ('Apple', 'Mango', 'Ban
5 min read
Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Python | Pair and combine nested list to tuple list
Sometimes we need to convert between the data types, primarily due to the reason of feeding them to some function or output. This article solves a very particular problem of pairing like indices in list of lists and then construction of list of tuples of those pairs. Let's discuss how to achieve the solution of this problem. Method #1 : Using zip()
10 min read
Python | Cumulative Nested Tuple Column Product
Sometimes, while working with records, we can have a problem in which we require to perform index wise multiplication of tuple elements. This can get complicated with tuple elements to be tuple and inner elements again be tuple. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using zip() + nested generator expression The
7 min read
Python - Remove nested records from tuple
Sometimes, while working with records, we can have a problem in which an element of a record is another tuple records and we might have to remove the nested records. This is a problem which does not occur commonly, but having a solution to it is useful. Let’s discuss certain way in which this task can be performed. Method 1: Using loop + isinstance
5 min read
Python - Convert Nested Tuple to Custom Key Dictionary
Sometimes, while working with Python records, we can have data that come without proper column names/identifiers, which can just be identified by their index, but we intend to assign them keys and render in form of dictionaries. This kind of problem can have applications in domains such as web development. Let's discuss certain ways in which this t
4 min read
Python - Convert Nested dictionary to Mapped Tuple
Sometimes, while working with Python dictionaries, we can have a problem in which we need to convert nested dictionaries to mapped tuple. This kind of problem can occur in web development and day-day programming. Let's discuss certain ways in which this task can be performed. Input : test_dict = {'gfg' : {'x' : 5, 'y' : 6, 'z': 3}, 'best' : {'x' :
4 min read
Practice Tags :
three90RightbarBannerImg