Python | Counting the Nth element of a tuple



Method # 1: Using Counter () + Expression Generator
A combination of the above functions can be used to achieve this particular task. In this, we iterate over a specific index using a generator expression and calculate the quantity using Counter () .

# Python3 demo code work
# Counting the Nth element of the tuple
# using Counter () + generator expression

from collections import Counter

 
# initialize the list

test_list = [( `gfg` , 0 ), ( `is` , 1 ), ( `best` , 2 ),

  ( `gfg` , 2 ), ( `is` , 0 ), ( `for` , 1 ),

  ( `geeks` , 2 )]

 
# print original list

print ( "The original list:" + str (test_list))

 
# initialize N

N = 1

 
# Counting the Nth element of the tuple
# using Counter () + generator expression

res = dict (Counter (sub [N] for sub in test_list))

 
# print 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}

Method # 2: Using Counter () + map () + itemgetter ()
A combination of the above functions can be used to solve this tasks. This does the task performed by the generator expression map () and itemgetter () is used to get the index of the container item.

# Python3 code to demonstrate how it works
# Counting the Nth element of the tuple
# using Counter () + map () + itemgetter ()

from collections import Counter

from operator import itemgetter

 
# initialize the list

test_list = [( `gfg` , 0 ), ( `is` , 1 ), ( `best` , 2 ), 

( `gfg` , 2 ), ( `is` , 0 ), ( `for` , 1 ),

( `geeks` , 2 )]

  
# print original list

print ( "The original list:" + str (test_list))

 
# initialize N

N = 1

 
# Counting the Nth element of the tuple
# using Counter () + map () + itemgetter ()

res = dict (Counter ( map (itemgetter (N), test_list)))

  
# print result

print ( "The grouped Nth element frequency is:" + str (res))

Exit:

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}