Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Minimum in each record value list
When working with nested lists in Python, finding the minimum value in each sublist is a common task. This article explores three different approaches to extract minimum values from each record in a list of lists.
Understanding the Problem
Given a list containing multiple sublists, we need to find the minimum value from each sublist. For example, if we have [[8,10,12], [12, 14, 16], [17, 18, 19]], the minimum values are 8, 12, and 17 respectively, giving us the result [8, 12, 17].
Method 1: Using List Comprehension with min()
The most Pythonic approach uses list comprehension combined with the built-in min() function ?
record = [[81, 102, 123], [124, 145, 166], [177, 188, 199]]
# Find minimum value in each sublist
min_values = [min(sublist) for sublist in record]
print("Minimum values:", min_values)
Minimum values: [81, 124, 177]
Method 2: Using a For Loop
A traditional iterative approach using a for loop to traverse each sublist ?
record = [[81, 102, 123], [124, 145, 166], [177, 188, 199]]
# Initialize empty list to store minimum values
min_items = []
# Iterate through each sublist
for sublist in record:
min_item = min(sublist)
min_items.append(min_item)
print("Minimum values:", min_items)
Minimum values: [81, 124, 177]
Method 3: Using map() Function
The map() function applies min() to each sublist and returns an iterator ?
record = [[81, 102, 123], [124, 145, 166], [177, 188, 199]]
# Use map to apply min function to each sublist
min_items = list(map(min, record))
print("Minimum values:", min_items)
Minimum values: [81, 124, 177]
Working with Mixed Data Types
Here's an example with unsorted sublists containing different values ?
mixed_record = [[25, 10, 30], [5, 18, 2], [100, 50, 75]]
# Using list comprehension
result = [min(sublist) for sublist in mixed_record]
print("Original data:", mixed_record)
print("Minimum values:", result)
Original data: [[25, 10, 30], [5, 18, 2], [100, 50, 75]] Minimum values: [10, 2, 50]
Comparison of Methods
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | High | Fast | Most Python code |
| For Loop | High | Moderate | Complex logic needed |
| map() Function | Moderate | Fast | Functional programming style |
Time Complexity
All three methods have a time complexity of O(n × m), where n is the number of sublists and m is the average length of each sublist. The space complexity is O(n) for storing the result list.
Conclusion
List comprehension with min() is the most Pythonic and efficient approach for finding minimum values in each sublist. Use the for loop method when you need additional processing logic, and map() for functional programming style.
