Python | Finding frequency in list of tuples
Last Updated :
15 May, 2023
In python we need to handle various forms of data and one among them is list of tuples in which we may have to perform any kind of operation. This particular article discusses the ways of finding the frequency of the 1st element in list of tuple which can be extended to any index. Let's discuss certain ways in which this can be performed.
Method #1 : Using map() + count() The map function can be used to accumulate the indices of all the tuples in a list and the task of counting the frequency can be done using the generic count function of python library.
Python3
# Python3 code to demonstrate
# finding frequency in list of tuples
# using map() + count()
# initializing list of tuples
test_list = [('Geeks', 1), ('for', 2), ('Geeks', 3)]
# printing the original list
print ("The original list is : " + str(test_list))
# using map() + count()
# finding frequency in list of tuples
res = list(map(lambda i : i[0], test_list)).count('Geeks')
# printing result
print ("The frequency of element is : " + str(res))
OutputThe original list is : [('Geeks', 1), ('for', 2), ('Geeks', 3)]
The frequency of element is : 2
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2 : Using Counter() + list comprehension List comprehension performs the task of getting the first element of the tuples and the counting part is handled by Counter function of collection library.
Python3
# Python3 code to demonstrate
# finding frequency in list of tuples
# using Counter() + list comprehension
from collections import Counter
# initializing list of tuples
test_list = [('Geeks', 1), ('for', 2), ('Geeks', 3)]
# printing the original list
print ("The original list is : " + str(test_list))
# using Counter() + list comprehension
# finding frequency in list of tuples
res = Counter(i[0] for i in test_list)
# printing result
print ("The frequency of element is : " + str(res['Geeks']))
OutputThe original list is : [('Geeks', 1), ('for', 2), ('Geeks', 3)]
The frequency of element is : 2
Method #3 : Dictionary comprehension and the get() method
To use dictionary comprehension and the get() method to find the frequency of the element 'Geeks' in the list of tuples test_list, you can do the following:
Python3
# initializing list of tuples
test_list = [('Geeks', 1), ('for', 2), ('Geeks', 3)]
# create a dictionary to store the frequency of each element looping and the get() method
frequency = {}
for element in test_list:
frequency[element[0]] = frequency.get(element[0], 0) + 1
# print the frequency of the element 'Geeks'
print(frequency['Geeks'])
#This code is contributed by Edula Vinay Kumar Reddy
If the element is already in the dictionary, the get() method returns its current value, and this value is incremented by 1. This allows us to count the frequency of each element in the list of tuples.
Time complexity: O(n)
Auxiliary Space: O(n)
Method #4 : Using map() + operator.countOf() method
The map function can be used to accumulate the indices of all the tuples in a list and the task of counting the frequency can be done using the operator.countOf function of python library.
Python3
# Python3 code to demonstrate
# finding frequency in list of tuples
# using map() + operator.countOf()
import operator as op
# initializing list of tuples
test_list = [('Geeks', 1), ('for', 2), ('Geeks', 3)]
# printing the original list
print ("The original list is : " + str(test_list))
# using map() + operator.countOf()
# finding frequency in list of tuples
res = op.countOf(list(map(lambda i : i[0], test_list)),'Geeks')
# printing result
print ("The frequency of element is : " + str(res))
OutputThe original list is : [('Geeks', 1), ('for', 2), ('Geeks', 3)]
The frequency of element is : 2
Time complexity: O(n*n)
Auxiliary Space: O(1)
Method #5: Using np.unique
The np.unique function in NumPy can be used to find the unique elements in a given array and their frequencies.
Algorithm:
- Initialize a NumPy array with the first elements of each tuple in the list of tuples.
- Use np.unique with the return_counts parameter set to True to get the unique elements and their frequencies.
- Find the index of the element to get its frequency.
Python3
# Python3 code to demonstrate
# finding frequency in list of tuples
# using np.unique
import numpy as np
# initializing list of tuples
test_list = [('Geeks', 1), ('for', 2), ('Geeks', 3)]
# printing the original list
print("The original list is : " + str(test_list))
# initializing NumPy array with first elements of tuples
arr = np.array([t[0] for t in test_list])
# using np.unique to get unique elements and their frequencies
unique, counts = np.unique(arr, return_counts=True)
# finding the index of the element
index = np.where(unique == 'Geeks')[0][0]
# printing result
print("The frequency of element is : " + str(counts[index]))
Output:
The original list is : [('Geeks', 1), ('for', 2), ('Geeks', 3)]
The frequency of element is : 2
Time Complexity: O(n log n), where n is the length of the list test_list (due to the sorting operation performed by np.unique).
Auxiliary Space: O(n), where n is the number of elements in the NumPy array arr.
METHOD 6:Using re-module.
APPROACH:
This program uses regular expressions in Python to find the frequency of a given element in a list of tuples. The program first creates a regular expression pattern that matches strings that start with the desired element followed by a word boundary. It then uses a generator expression to iterate over the list of tuples and count the number of tuples whose first element matches the pattern. Finally, it prints the result.
ALGORITHM:
1. Initialize the list of tuples and the element to be searched for.
2. Create a regular expression pattern that matches strings starting with the desired element followed by a word boundary.
3. Use a generator expression to iterate over the list of tuples and count the number of tuples whose first element matches the pattern.
4. Print the result.
Python3
import re
lst = [('Geeks', 1), ('for', 2), ('Geeks', 3)]
element = 'Geeks'
pattern = re.compile(rf"^{element}\b")
count = sum(1 for tpl in lst if pattern.match(tpl[0]))
print("The frequency of", element, "is", count)
OutputThe frequency of Geeks is 2
Time complexity:
The time complexity of this program is O(n), where n is the number of tuples in the list. This is because the program needs to iterate over each tuple in the list once to count the frequency of the desired element.
Space complexity:
The space complexity of this program is O(1), as the program only uses a constant amount of additional memory to store the regular expression pattern, the count variable, and the element to be searched for. The memory used by the list of tuples is not counted, as it is part of the input.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read