Python | Counting Nth tuple element
Last Updated :
21 Apr, 2023
Sometimes, while working with Python, we can have a problem in which we need to count the occurrence of a particular's elements. This kind of problem is quite common while working with records. Let's discuss a way in which this task can be performed.
Method #1 : Using Counter() + generator expression The combination of above functionalities can be used to achieve this particular task. In this, we iterate through a specific index using generator expression and compute the count using Counter().
Python3
# Python3 code to demonstrate working of
# Counting Nth tuple element
# using Counter() + generator expression
from collections import Counter
# initialize list
test_list = [('gfg', 0), ('is', 1), ('best', 2),
('gfg', 2), ('is', 0), ('for', 1),
('geeks', 2)]
# printing original list
print("The original list : " + str(test_list))
# initialize N
N = 1
# Counting Nth tuple element
# using Counter() + generator expression
res = dict(Counter(sub[N] for sub in test_list))
# printing result
print("The grouped Nth element frequency is : " + str(res))
Output :
The original list : [('gfg', 0), ('is', 1), ('best', 2), ('gfg', 2), ('is', 0), ('for', 1), ('geeks', 2)] The grouped Nth element frequency is : {0: 2, 1: 2, 2: 3}
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. Counter() + generator expression performs n*n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list
Method #2 : Using Counter() + map() + itemgetter() The combination of above functions can be used to achieve this task. In this, the task performed by generator expression is performed by map() and itemgetter() is used to get the index of the container element.
Python3
# Python3 code to demonstrate working of
# Counting Nth tuple element
# using Counter() + map() + itemgetter()
from collections import Counter
from operator import itemgetter
# initialize list
test_list = [('gfg', 0), ('is', 1), ('best', 2),
('gfg', 2), ('is', 0), ('for', 1),
('geeks', 2)]
# printing original list
print("The original list : " + str(test_list))
# initialize N
N = 1
# Counting Nth tuple element
# using Counter() + map() + itemgetter()
res = dict(Counter(map(itemgetter(N), test_list)))
# printing result
print("The grouped Nth element frequency is : " + str(res))
Output :
The original list : [('gfg', 0), ('is', 1), ('best', 2), ('gfg', 2), ('is', 0), ('for', 1), ('geeks', 2)] The grouped Nth element frequency is : {0: 2, 1: 2, 2: 3}
Time Complexity: O(n*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 #3: Using for loop and dictionary ().
we use a for loop and a dictionary to count the frequency of the N th element of each tuple in a given list of tuples. The input list, "test_list," contains tuples with various words as the first element and a number as the N th element. The for loop iterates over each tuple in the list, and if the N th element of the tuple is already a key in the dictionary "dic," the value associated with that key is incremented by one. If the N th element of the tuple is not a key in the dictionary, a new key is created with a value of one. After the for loop completes, the dictionary "dic" contains the frequency of each N th element in the input list, and this is printed to the console.
Python3
# Python3 code to demonstrate working of
# Counting Nth tuple element
# using for loop and dictionary
from collections import Counter
from operator import itemgetter
# initialize list
test_list = [('gfg', 0), ('is', 1), ('best', 2),
('gfg', 2), ('is', 0), ('for', 1),
('geeks', 2)]
# printing original list
print('The original list :' + str(test_list))
# initialize N
N = 1
dic={}
# Counting Nth tuple element
for i in test_list:
if i[N] in dic:
dic[i[N]]+=1
else:
dic[i[N]]=1
# printing result
print('The grouped Nth element frequency is : ' + str(dic))
#this code contributed by tvsk
OutputThe original list :[('gfg', 0), ('is', 1), ('best', 2), ('gfg', 2), ('is', 0), ('for', 1), ('geeks', 2)]
The grouped Nth element frequency is : {0: 2, 1: 2, 2: 3}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4 : Using count(), list(), set() methods
- Extract Nth column values from a list of tuples(test_list) using a for loop and store in the variable x.
- Remove duplicates from x (using list(), set())and store it in y, creating an empty dictionary res.
- Initialize the dictionary res with values of y as keys and count of these keys in x as values(using count()).
- Display res.
Python3
# Python3 code to demonstrate working of
# Counting Nth tuple element
# initialize list
test_list = [('gfg', 0), ('is', 1), ('best', 2),
('gfg', 2), ('is', 0), ('for', 1),
('geeks', 2)]
# printing original list
print("The original list : " + str(test_list))
# initialize N
N = 1
# Counting Nth tuple element
res = dict()
x = []
for i in test_list:
x.append(i[N])
y = list(set(x))
for i in y:
res[i] = x.count(i)
# printing result
print("The grouped Nth element frequency is : " + str(res))
OutputThe original list : [('gfg', 0), ('is', 1), ('best', 2), ('gfg', 2), ('is', 0), ('for', 1), ('geeks', 2)]
The grouped Nth element frequency is : {0: 2, 1: 2, 2: 3}
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Python - Count elements in tuple list Sometimes, while working with data in form of records, we can have a problem in which we need to find the count of all the records received. This is a very common application that can occur in Data Science domain. Letâs discuss certain ways in which this task can be performed. Method #1: Using len()
5 min read
Python - Count elements in record tuple Sometimes, while working with data in form of records, we can have a problem in which we need to find the total element counts of all the records received. This is a very common application that can occur in Data Science domain. Letâs discuss certain ways in which this task can be performed. Method
5 min read
Python Tuple count() Method In this article, we will learn about the count() method used for tuples in Python. The count() method of a Tuple returns the number of times the given element appears in the tuple. Example Python3 tuple = (1, 2, 3, 1, 2, 3, 1, 2, 3) print(tuple.count(3)) Output : 3Python Tuple count() Method Syntax
3 min read
Python | Tuple Column element frequency In Python, we need to handle various forms of data and one among them is a 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 Kth element in the list of tuples. Letâs discuss certain ways in which this can
5 min read
Python - Filter consecutive elements Tuples Given a Tuple list, filter tuples that are made from consecutive elements, i.e diff is 1. Input : test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 4), (6, 4, 6, 3)] Output : [(3, 4, 5, 6)] Explanation : Only 1 tuple adheres to condition. Input : test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6,
5 min read
Python - Get Nth column elements in Tuple Strings Yet another peculiar problem that might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This article solves the problem of extracting only the
8 min read