A list of tuples can be treated as a table where each tuple represents a row and each element represents a column. To find the minimum value of each column, we need to compare elements at the same position across all tuples.
test_list = [(1, 2, 3), (6, 7, 6), (1, 6, 8)]
res = [min(col) for col in zip(*test_list)]
print(res)
Output
[1, 2, 3]
Explanation:
- *test_list unpacks all tuples.
- zip() groups elements having the same position.
- min() finds the smallest element in each column.
- List comprehension stores all minimum values in a list.
Using zip(), map() and min()
Similar, result can be obtained using map(). It applies min() to every column generated by zip().
test_list = [(1, 2, 3), (6, 7, 6), (1, 6, 8)]
res = list(map(min, zip(*test_list)))
print(res)
Output
[1, 2, 3]
Explanation:
- zip(*test_list) creates columns from the tuples.
- map(min, ...) applies min() to each column.
- list() converts the result into a list.
Using NumPy
It can calculate column-wise minimum values with np.min(). The axis=0 argument tells NumPy to perform the operation column-wise.
import numpy as np
test_list = [(1, 2, 3), (6, 7, 6), (1, 6, 8)]
arr = np.array(test_list)
res = np.min(arr, axis=0)
print(res)
Output
[1 2 3]
Explanation:
- np.array() converts the list of tuples into an array.
- axis=0 selects columns.
- np.min() finds the minimum value from each column.
Using For Loop and min()
This operation can also be performed with loops.
Example:
test_list = [(1, 2, 3), (6, 7, 6), (1, 6, 8)]
res = []
for i in range(len(test_list[0])):
column = []
for row in test_list:
column.append(row[i])
res.append(min(column))
print(res)
Output
[1, 2, 3]
Explanation:
- Outer loop selects each column.
- Inner loop collects values from that column.
- min() finds the smallest value.
- Result is added to the output list.
Handling Unequal Tuple Lengths
zip() approach works best when all tuples have the same length. By default, zip() stops when the shortest tuple is exhausted.
test_list = [(1, 2, 3), (4, 5), (6, 7, 8)]
res = [min(col) for col in zip(*test_list)]
print(res)
Output
[1, 2]
Third column is ignored because the second tuple does not contain a third element.
Time and Space Complexity
- For N tuples and M columns, every available value is processed once.
- Time Complexity: O(N x M)
- Result contains M minimum values. Intermediate storage depends on the method used.