Open In App

Python - Find maximum value in each sublist

Last Updated : 24 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Finding the maximum value in each sublist involves iterating through a list of lists and identifying the largest element within each sublist. This operation is useful for analyzing data sets, and extracting the most significant values from grouped information. In this article, we will explore methods to find maximum value.

Using map()

map() function applies a specified function, max() to each sublist in the list of lists. It processes each sublist and returns the result in a new list.

Example:

Python
a = [[10, 13, 454, 66, 44], [10, 8, 7, 23]]

# Using map with max
res = list(map(max,a))
print(res)

Output
[454, 23]

Explanation:

  • It applies max() to each sublist in a.
  • It returns the maximum value from each sublist .

Let's understand more methods to find maximum in each sublist.

Using list comprehension

list comprehension with max() is a simple way to get the highest value from each sublist. It works well for medium-sized datasets, balancing speed and ease of understanding.

Example:

Python
a = [[10, 13, 454, 66, 44], [10, 8, 7, 23]]

# Using list comprehension with max()
res = [max(sublist) for sublist in a]
print(res)

Output
[454, 23]

Explanation:

  • It applies max() to each sublist in a.
  • It returns the maximum value from each sublist .

Using reduce()

reduce() function can be used to find the maximum value in each sublist by iterating through the elements. This approach maintains the order of the sublists while calculating the maximum.

Example:

Python
from functools import reduce

a = [[10, 13, 454, 66, 44], [10, 8, 7, 23]]

# Using reduce to find the max value in each sublist
res = [reduce(lambda x, y: x if x > y else y, sublist) for sublist in a]

print(res) 

Output
[454, 23]

Explanation:

  • This code finds the maximum value in each sublist.
  • It returns the results .

Using for loop

for loop find the highest value in each sublist. It processes each sublist one by one and adds the maximum value to the result.

Example:

Python
a = [[10, 13, 454, 66, 44], [10, 8, 7, 23]]

# Using for loop with max()
res = []

for sublist in a:
    res.append(max(sublist))
    
print(res) 

Output
[454, 23]

Explanation:

  • It finds the maximum value in each sublist.
  • It adds the results to the res list.

Next Article
Practice Tags :

Similar Reads