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
Selected Reading
Python – Maximum in Row Range
When it is required to find the maximum value in a row range, a simple iteration and the max() method is used.
Example
Below is a demonstration of finding the maximum value across specified rows ?
my_list = [[11, 35, 6], [9, 11, 3], [35, 4, 2], [8, 15, 35], [5, 9, 18], [5, 14, 2]]
print("The list is :")
print(my_list)
i, j = 2, 4
print("The row range values are")
print(i, j)
my_result = 0
for index in range(i, j):
my_result = max(max(my_list[index]), my_result)
print("The maximum value in row range is :")
print(my_result)
Output
The list is : [[11, 35, 6], [9, 11, 3], [35, 4, 2], [8, 15, 35], [5, 9, 18], [5, 14, 2]] The row range values are 2 4 The maximum value in row range is : 35
How It Works
- A list of lists is defined with 6 rows of data
- The range values
i=2andj=4specify rows 2 and 3 (indices 2 to 3) - The algorithm iterates through the specified row range
- For each row,
max(my_list[index])finds the maximum value in that row - The outer
max()compares this with the current result to keep the overall maximum - Row 2: [35, 4, 2] ? max = 35
- Row 3: [8, 15, 35] ? max = 35
- Overall maximum = 35
Alternative Approach Using List Comprehension
You can achieve the same result more concisely using list comprehension ?
my_list = [[11, 35, 6], [9, 11, 3], [35, 4, 2], [8, 15, 35], [5, 9, 18], [5, 14, 2]]
i, j = 2, 4
result = max(max(row) for row in my_list[i:j])
print(f"Maximum value in rows {i} to {j-1}: {result}")
Maximum value in rows 2 to 3: 35
Conclusion
Use nested max() functions to find the maximum value across a specific row range in a 2D list. The list comprehension approach provides a more concise solution for the same problem.
Advertisements
