The task of finding the minimum and maximum values in a list of tuples in Python involves identifying the smallest and largest elements from each position (column) within the tuples. For example, given [(2, 3), (4, 7), (8, 11), (3, 6)], the first elements (2, 4, 8, 3) have a minimum of 2 and a maximum of 8, while the second elements (3, 7, 11, 6) have a minimum of 3 and a maximum of 11. The result is (2, 8) for the first column and (3, 11) for the second.
Using zip()
zip(*a) transposes the list of tuples, effectively grouping each element from corresponding positions (columns) into separate sequences. We can then apply min() and max() directly to each sequence.
a = [(2, 3), (4, 7), (8, 11), (3, 6)]
x, y = zip(*a)
res1 = (min(x), max(x)) # first
res2 = (min(y), max(y)) # second
print(res1)
print(res2)
Output
(2, 8) (3, 11)
Explanation: zip(*a) transposes the list of tuples, grouping first and second elements separately. min() and max() are applied to each group, forming res1 and res2 with the minimum and maximum values.
Table of Content
Using generator function
This method manually extracts elements from each tuple using generator function. These elements are then passed into min() and max() functions.
a = [(2, 3), (4, 7), (8, 11), (3, 6)]
res1 = (min(x[0] for x in a), max(x[0] for x in a))
res2 = (min(x[1] for x in a), max(x[1] for x in a))
print(res1)
print(res2)
Output
(2, 8) (3, 11)
Explanation:(x[0] for x in a) extracts the first element from each tuple and (x[1] for x in a) extracts the second. min() and max() are applied to both sequences, forming tuples res1 and res2 with the minimum and maximum values.
Using map()
This method manually extracts elements from each tuple using map() and lambda functions. These elements are then passed into min() and max() functions.
a = [(2, 3), (4, 7), (8, 11), (3, 6)]
res1 = (min(map(lambda x: x[0], a)), max(map(lambda x: x[0], a)))
res2 = (min(map(lambda x: x[1], a)), max(map(lambda x: x[1], a)))
print(res1)
print(res2)
Output
(2, 8) (3, 11)
Explanation: map(lambda x: x[0], a) and map(lambda x: x[1], a) extract the first and second elements from each tuple. min() and max() are applied to get res1 and res2 with the minimum and maximum values.
Using pandas
Pandas is an external library designed for data analysis. It treats tuples as rows and creates columns for their elements. We can leverage .min() and .max() on each column.
import pandas as pd
a = [(2, 3), (4, 7), (8, 11), (3, 6)]
df = pd.DataFrame(a, columns=['first', 'second']) # convert`a` to panda dataframe
res1 = (df['first'].min(), df['first'].max())
res2 = (df['second'].min(), df['second'].max())
print(res1)
print(res2)
Output
(np.int64(2), np.int64(8)) (np.int64(3), np.int64(11))
Explanation: df['first'].min() and df['first'].max() get the minimum and maximum values from the 'first' column, forming res1. Similarly, df['second'].min() and df['second'].max() form res2 from the 'second' column.