# Python | Top N pairs by element Kth from the list

Python Methods and Functions

Method # 1: Using ` filter () + lambda + set () ` + list comprehension

A combination of the above functions can be used to accomplish this particular functions. In doing so, we first filter the top N elements from the K-th index, and then apply those values ​​to the list and return the result.

 ` # Python3 code to demonstrate how it works ` ` # The best N pairs for the Kth element from the list ` ` # Using the filter () + lambda + set ( ) + list comprehension `   ` # initialize the list ` ` test_list ` ` = ` ` [(` `' gfg' ` `, ` ` 4 ` `, ` ` 'good' ` `), (` `' gfg' ` `, ` ` 2 ` `, 'better' ), ``   ( 'gfg' , 1 , 'best' ), ( 'gfg' , 3 , 'geeks' )]    # print the original list print ( "The original list is:" + str (test_list))   # initialize N N = 3     # initialize K K = 1   # Top N pairs for the Kth element from the list # Using filter () + lambda + set () + list comprehension temp = set ( list ({sub [K] for sub in test_list}) [ - N:]) res = list (  filter ( lambda sub: sub [K] in temp, test_list))   # print result print ( "Top N elements of Kth index are:" + str (res)) `

Output:

The original list is: [('gfg', 4, 'good'), ('gfg', 2, 'better '), (' gfg ', 1,' best '), (' gfg ', 3,' geeks')]
Top N elements of Kth index are: [('gfg', 4, 'good' ), ('gfg', 2, 'better'), ('gfg', 3, 'geeks')]

Method # 2: Using ` groupby ( ) + sorted () ` + loop

This task can also be performed using a using the above functions. In this, we will first group the top N elements together and then constrain them by N when building the list of results.

 ` # Python3 code to demonstrate how it works ` ` # Top N pairs for the Kth element from the list ` ` # Using groupby () + sorted () + loop ` ` import ` ` itertools `   ` # initialize the list ` ` test_list ` ` = ` ` [(` ` 'gfg' ` `, ` ` 4 ` `, ` ` 'good' ` `), ( ` ` 'gfg' ` `, ` 2 `, ` ` 'better' ` `), ` ` (` ` 'gfg' ` `, ` ` 1 ` `, ` ` 'best '` `), (` `' gfg' ` `, ` ` 3 ` `, ` ` 'geeks' ` `)] `   ` # print original list ` ` print ` ` (` ` "The original list is:" ` ` + ` ` str ` ` (test_list)) ` ` `  ` # initialize N `` N = 3     # initialize K K = 1    # Top N pairs for the Kth element from the list # Using groupby () + sorted () + loop res = [] temp = itertools.groupby ( sorted (test_list, key = lambda sub: sub [K],  reverse = True ), key = lambda sub: sub [K]) for i in range (N): res.extend ( list ( next (temp) [K]))   # print result print ( "Top N elements of Kth index are:" + str (res)) `

Output:

The original list is: [('gfg', 4, 'good'), ('gfg', 2, 'better'), ('gfg', 1, 'best'), ('gfg', 3, 'geeks ')]
Top N elements of Kth index are: [(' gfg ', 4,' good '), (' gfg ', 2,' better '), (' gfg ', 3,' geeks' )]