Find minimum k records from tuple list in Python

PythonServer Side ProgrammingProgramming

When it is required to find the minimum 'k' records from a list of tuples, it can be done using the 'sorted' method and lambda function.

The 'sorted' method is used to sort the elements of a list. Anonymous function is a function which is defined without a name.

In general, functions in Python are defined using 'def' keyword, but anonymous function is defined with the help of 'lambda' keyword. It takes a single expression, but can take any number of arguments. It uses the expression and returns the result of it.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

A list of tuple basically contains tuples enclosed in a list.

Below is a demonstration of the same −

Example

Live Demo

my_list = [( 67, 'Will'), (34, 'Mark'), (99, 'Dev'), (2, 'Paul')]

print ("The list is : " )
print(my_list)
K = 3
print("The value of 'K' has been initialized")

my_result = sorted(my_list, key = lambda x: x[1])[:K]

print("The lowest " + str(K) + " records are : ")
print(my_result)

Output

The list is :
[(67, 'Will'), (34, 'Mark'), (99, 'Dev'), (2, 'Paul')]
The value of 'K' has been initialized
The lowest 3 records are :
[(99, 'Dev'), (34, 'Mark'), (2, 'Paul')]

Explanation

  • A list of tuples is defined, and displayed on the console.
  • The value of 'K' is initialized.
  • The sorted method is used to sort the list of tuples, based on the lambda function which is defined inside it.
  • This operation is assigned a variable.
  • This variable is the output that is displayed on the console.
raja
Published on 11-Mar-2021 09:29:29
Advertisements