
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Find minimum k records from tuple list in Python
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
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.
- Related Articles
- Maximum and Minimum K elements in Tuple using Python
- Remove nested records from tuple in Python
- Extract digits from Tuple list Python
- Intersection in Tuple Records Data in Python
- Program to find minimum possible sum by changing 0s to 1s k times from a list of numbers in Python?
- Create a tuple from string and list in Python
- Find top K frequent elements from a list of tuples in Python
- Flatten tuple of List to tuple in Python
- Get maximum of Nth column from tuple list in Python
- Rear element extraction from list of tuples records in Python
- Test if Tuple contains K in Python
- Program to find k-sized list where difference between largest and smallest item is minimum in Python
- Get minimum difference in Tuple pair in Python
- Program to find sum of minimum trees from the list of leaves in python
- Find k longest words in given list in Python

Advertisements