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
Find maximum value in each sublist in Python
We are given a list of lists (nested lists). Our task is to find the maximum value in each sublist and return them as a new list. Python provides several approaches to accomplish this efficiently.
Using List Comprehension with max()
The most Pythonic approach uses list comprehension combined with the max() function to iterate through each sublist ?
data = [[10, 13, 454, 66, 44], [10, 8, 7, 23], [5, 15, 25]]
# Given list
print("The given list:")
print(data)
# Use max with list comprehension
result = [max(sublist) for sublist in data]
print("Maximum values from each sublist:")
print(result)
The given list: [[10, 13, 454, 66, 44], [10, 8, 7, 23], [5, 15, 25]] Maximum values from each sublist: [454, 23, 25]
Using map() with max()
The map() function applies max() to each sublist and returns an iterator, which we convert to a list ?
data = [[10, 13, 454, 66, 44], [10, 8, 7, 23], [5, 15, 25]]
# Given list
print("The given list:")
print(data)
# Use map with max
result = list(map(max, data))
print("Maximum values from each sublist:")
print(result)
The given list: [[10, 13, 454, 66, 44], [10, 8, 7, 23], [5, 15, 25]] Maximum values from each sublist: [454, 23, 25]
Using a For Loop
For beginners, a traditional for loop approach provides clear step-by-step logic ?
data = [[10, 13, 454, 66, 44], [10, 8, 7, 23], [5, 15, 25]]
# Given list
print("The given list:")
print(data)
# Using for loop
result = []
for sublist in data:
result.append(max(sublist))
print("Maximum values from each sublist:")
print(result)
The given list: [[10, 13, 454, 66, 44], [10, 8, 7, 23], [5, 15, 25]] Maximum values from each sublist: [454, 23, 25]
Handling Empty Sublists
When sublists might be empty, we need to handle the ValueError that max() raises ?
data = [[10, 13, 454], [], [5, 15, 25]]
result = []
for sublist in data:
if sublist: # Check if sublist is not empty
result.append(max(sublist))
else:
result.append(None) # or 0, or any default value
print("Maximum values (handling empty sublists):")
print(result)
Maximum values (handling empty sublists): [454, None, 25]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | High | Fast | Most scenarios |
| map() function | Medium | Fast | Functional programming style |
| For Loop | High | Slower | Complex logic or error handling |
Conclusion
List comprehension with max() is the most Pythonic and efficient approach for finding maximum values in sublists. Use map() for functional programming style, and traditional loops when you need complex error handling or additional logic.
