Open In App

Python | Count tuples occurrence in list of tuples

Last Updated : 01 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Many a time while developing web and desktop products in Python, we use nested lists and have several queries about how to find the count of unique tuples. Let us see how to get the count of unique tuples in the given list of tuples. Below are some ways to achieve the above task.

Method #1: Using Iteration 

Python3




# Python code to count unique
# tuples in list of list
 
import collections
Output = collections.defaultdict(int)
 
# List initialization
Input = [[('hi', 'bye')], [('Geeks', 'forGeeks')],
         [('a', 'b')], [('hi', 'bye')], [('a', 'b')]]
 
# Using iteration
for elem in Input:
      Output[elem[0]] += 1
     
# Printing output
print(Output)


Output:

defaultdict(<class 'int'>, {('Geeks', 'forGeeks'): 1, ('hi', 'bye'): 2, ('a', 'b'): 2})

Time complexity: O(n), where n is the total number of tuples in the list of lists.
Auxiliary space: O(m), where m is the total number of unique tuples in the list of lists.

Method #2: Using chain and Counter 

Python3




# Python code to count unique
# tuples in list of list
 
# Importing
from collections import Counter
from itertools import chain
 
# List initialization
Input = [[('hi', 'bye')], [('Geeks', 'forGeeks')],
         [('a', 'b')], [('hi', 'bye')], [('a', 'b')]]
 
# Using counter and chain
Output = Counter(chain(*Input))
 
# Printing output
print(Output)


Output:

Counter({('hi', 'bye'): 2, ('a', 'b'): 2, ('Geeks', 'forGeeks'): 1})

Time complexity: O(n), where n is the total number of tuples in the input list of lists. 
Auxiliary space: O(n), as we are using a Counter object to store the counts of each unique tuple, which can take up to n space in the worst case. 

Method #3: List Comprehension method

Python3




Input = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]
check_ele=('a', 'b')
x=[i for i in Input if i==check_ele]
print("tuple ('a', 'b') occurs",len(x),"times")


Output

tuple ('a', 'b') occurs 2 times

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(k), where k is the number of occurrences of the check element in the input list.

Method #4: Using enumerate function

Python3




Input = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]
check_ele=('a', 'b')
x=[i for a,i in enumerate(Input) if i==check_ele]
print("tuple ('a', 'b') occurs",len(x),"times")


Output

tuple ('a', 'b') occurs 2 times

Time complexity: O(n), where n is the length of the input list ‘Input’.
Auxiliary space: O(m), where m is the number of occurrences of the tuple ‘check_ele’ in the input list ‘Input’

Method #5: Using lambda function 

Python3




Input = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]
check_ele=('a', 'b')
x=list(filter(lambda i:(i==check_ele),Input))
print("tuple ('a', 'b') occurs",len(x),"times")


Output

tuple ('a', 'b') occurs 2 times

Time complexity: O(n), where n is the number of tuples in the Input list.
Auxiliary space: O(1) because it uses only a constant amount of extra space to store the filtered list and the length of that list.

Method #6: Using only Counter function 

Python3




from collections import Counter
Input = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]
check_ele=('a', 'b')
x=Counter(Input)
print("tuple ('a', 'b') occurs",x[check_ele],"times")


Output

tuple ('a', 'b') occurs 2 times

Time complexity: O(n), where n is the number of tuples in the Input list.
Auxiliary space: O(n), where n is the number of tuples in the Input list. 

Method #7: Using countof function

Python3




import operator as op
Input = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]
check_ele=('a', 'b')
print(op.countOf(Input,check_ele))


Output

2

Time complexity: O(n), where n is the length of the input list. 
Auxiliary space: O(n), because the list comprehension creates a new list of all occurrences of the check_ele tuple.

Method #8: Using dict() method 

Creating empty dictionary and iterating every element in list. Checking if element in dictionary increment value of key i by 1 else assign the key to element i with 1. finally, the dictionary will have keys as elements and their values as count of element in list.

Python3




#Initializing tuples in a list
Input = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]
#creating empty dictionary 
count_tuples=dict()
#using for loop to iterate every value in Input
for i in Input:
  if i not in count_tuples:   #checking if element i present in dictionary  or not
    count_tuples[i]=1
  else:
    count_tuples[i]+=1
#printing dictionary  of elements and their count
print(count_tuples)


Output

{('hi', 'bye'): 2, ('Geeks', 'forGeeks'): 1, ('a', 'b'): 2}

Time complexity: O(n), where n is the length of the input list. The for loop iterates over every element in the input list exactly once.

Auxiliary space: O(m), where m is the number of unique tuples in the input list. In the worst case, when all the tuples are unique, the dictionary will contain m key-value pairs.

Method #9:  Using map() function and tuple() constructor

This method involves mapping each list of tuples to a tuple of tuples and then counting the occurrences of each tuple in the list.

Python3




# Python code to count unique
# tuples in list of list
 
# List initialization
Input = [[('hi', 'bye')], [('Geeks', 'forGeeks')],
         [('a', 'b')], [('hi', 'bye')], [('a', 'b')]]
 
# Using map() function and tuple() constructor
Output = {}
for elem in Input:
    t = tuple(map(tuple, elem))
    Output[t] = Output.get(t, 0) + 1
 
# Printing output
print(Output)


Output

{(('hi', 'bye'),): 2, (('Geeks', 'forGeeks'),): 1, (('a', 'b'),): 2}

Time Complexity: O(nk), where n is the number of elements in the input list and k is the maximum number of tuples in a sublist.
Auxiliary Space: O(n), where n is the number of elements in the input list.

Method #10: Using set() and count()

  1. Initializes a list of tuples input_list containing five tuples.
  2. Converts the list to a set unique_set to remove duplicate tuples.
  3. Creates a dictionary output_dict where each key is a unique tuple from input_list, and each value is the count of that tuple in input_list.
  4. Prints the dictionary output_dict.

Python3




# Initializing tuples in a list
input_list = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]
 
# Converting list to set to remove duplicates
unique_set = set(input_list)
 
# Counting occurrences of each unique tuple
output_dict = {elem: input_list.count(elem) for elem in unique_set}
 
# Printing output
print(output_dict)


Output

{('a', 'b'): 2, ('hi', 'bye'): 2, ('Geeks', 'forGeeks'): 1}

The time complexity is O(n^2)

The auxiliary space is also O(n^2)



Similar Reads

Python | Remove duplicate tuples from list of tuples
Given a list of tuples, Write a Python program to remove all the duplicated tuples from the given list. Examples: Input : [(1, 2), (5, 7), (3, 6), (1, 2)] Output : [(1, 2), (5, 7), (3, 6)] Input : [('a', 'z'), ('a', 'x'), ('z', 'x'), ('a', 'x'), ('z', 'x')] Output : [('a', 'z'), ('a', 'x'), ('z', 'x')] Method #1 : List comprehension This is a naive
5 min read
Python | Find the tuples containing the given element from a list of tuples
Given a list of tuples, the task is to find all those tuples containing the given element, say n. Examples: Input: n = 11, list = [(11, 22), (33, 55), (55, 77), (11, 44)] Output: [(11, 22), (11, 44)] Input: n = 3, list = [(14, 3),(23, 41),(33, 62),(1, 3),(3, 3)] Output: [(14, 3), (1, 3), (3, 3)] There are multiple ways we can find the tuples contai
6 min read
Python | Remove tuples from list of tuples if greater than n
Given a list of a tuple, the task is to remove all the tuples from list, if it's greater than n (say 100). Let's discuss a few methods for the same. Method #1: Using lambda STEPS: Initialize a list of tuples: ini_tuple = [('b', 100), ('c', 200), ('c', 45), ('d', 876), ('e', 75)]Print the initial list: print("intial_list", str(ini_tuple))Define the
6 min read
Python | Remove tuples having duplicate first value from given list of tuples
Given a list of tuples, the task is to remove all tuples having duplicate first values from the given list of tuples. Examples: Input: [(12.121, 'Tuple1'), (12.121, 'Tuple2'), (12.121, 'Tuple3'), (923232.2323, 'Tuple4')] Output: [(12.121, 'Tuple1'), (923232.2323, 'Tuple4')]Input: [('Tuple1', 121), ('Tuple2', 125), ('Tuple1', 135), ('Tuple4', 478)]
7 min read
Python | Combining tuples in list of tuples
Sometimes, we might have to perform certain problems related to tuples in which we need to segregate the tuple elements to combine with each element of complex tuple element( such as list ). This can have application in situations we need to combine values to form a whole. Let's discuss certain ways in which this can be performed. Method #1: Using
7 min read
Python | Convert string tuples to list tuples
Sometimes, while working with Python we can have a problem in which we have a list of records in form of tuples in stringified form and we desire to convert them to a list of tuples. This kind of problem can have its occurrence in the data science domain. Let's discuss certain ways in which this task can be performed. Method 1 (Using eval() + list
4 min read
Python - Filter all uppercase characters Tuples from given list of tuples
Given a Tuple list, filter tuples that contain all uppercase characters. Input : test_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")] Output : [('GFG', 'IS', 'BEST')] Explanation : Only 1 tuple has all uppercase Strings. Input : test_list = [("GFG", "iS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")] Output : [
8 min read
Python program to find Tuples with positive elements in List of tuples
Given a list of tuples. The task is to get all the tuples that have all positive elements. Examples: Input : test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [(4, 5, 9)] Explanation : Extracted tuples with all positive elements. Input : test_list = [(-4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [] Explanation : No tuple wit
10 min read
Python program to find tuples which have all elements divisible by K from a list of tuples
Given a list of tuples. The task is to extract all tuples which have all elements divisible by K. Input : test_list = [(6, 24, 12), (60, 12, 6), (12, 18, 21)], K = 6 Output : [(6, 24, 12), (60, 12, 6)] Explanation : Both tuples have all elements multiple of 6. Input : test_list = [(6, 24, 12), (60, 10, 5), (12, 18, 21)], K = 5 Output : [(60, 10, 5)
7 min read
Generating a Set of Tuples from a List of Tuples in Python
Python provides a versatile set of tools for manipulating data structures, and when it comes to working with tuples, developers often need to extract unique elements or create a set of tuples from a given list. In this article, we will explore some simple and commonly used methods to generate a set of tuples from a list of tuples in Python. Generat
4 min read
Practice Tags :
three90RightbarBannerImg