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
Get maximum of Nth column from tuple list in Python
When working with a list of tuples, you may need to find the maximum value from a specific column (position). Python provides an elegant solution using list comprehension with the max() function.
The max() function returns the maximum value from an iterable, while list comprehension provides a concise way to extract elements from each tuple at a specific index position.
Basic Syntax
max([tuple[N] for tuple in tuple_list])
Where N is the column index (0-based) you want to find the maximum from.
Example
Let's find the maximum value from the 2nd column (index 2) of a tuple list ?
# List of tuples with student scores
scores = [(67, 78, 39), (34, 23, 52), (99, 69, 78), (2, 11, 0)]
print("The list is:")
print(scores)
# Find maximum from column 2 (3rd element of each tuple)
N = 2
print(f"Finding maximum from column {N}")
result = max([sub[N] for sub in scores])
print("The maximum of Nth column in the list of tuples is:")
print(result)
The list is: [(67, 78, 39), (34, 23, 52), (99, 69, 78), (2, 11, 0)] Finding maximum from column 2 The maximum of Nth column in the list of tuples is: 78
Alternative Methods
Using operator.itemgetter()
For better performance with large datasets ?
from operator import itemgetter
scores = [(67, 78, 39), (34, 23, 52), (99, 69, 78), (2, 11, 0)]
N = 2
result = max(scores, key=itemgetter(N))[N]
print(f"Maximum from column {N}: {result}")
Maximum from column 2: 78
Using zip() with Unpacking
Extract entire columns first, then find maximum ?
scores = [(67, 78, 39), (34, 23, 52), (99, 69, 78), (2, 11, 0)]
# Unpack and get all columns
columns = list(zip(*scores))
print("All columns:", columns)
# Get maximum from column 2
N = 2
result = max(columns[N])
print(f"Maximum from column {N}: {result}")
All columns: [(67, 34, 99, 2), (78, 23, 69, 11), (39, 52, 78, 0)] Maximum from column 2: 78
Comparison
| Method | Performance | Best For |
|---|---|---|
| List Comprehension | Good | Simple, readable code |
| itemgetter() | Best | Large datasets |
| zip() Unpacking | Good | Multiple column operations |
Conclusion
List comprehension with max() provides the most readable solution for finding maximum values from tuple columns. For performance-critical applications, consider using operator.itemgetter().
