In this tutorial, we will look at how to get the min value and its corresponding index in a tuple in Python with the help of some examples.
How to get the min value in a tuple?
You can use the Python built-in
min() function to get the min value in a tuple. Alternatively, you can also iterate through the tuple to find the minimum value.
Let’s look at the two methods with the help of examples.
The Python built-in
min() function returns the minimum value in an iterable. Pass the tuple as an argument to get its minimum value.
# create a tuple t = (2, 7, 5, 1, 4) # get min value in tuple print(min(t))
We get the minimum value of the tuple
To get the index corresponding to the min value, you can use the tuple’s
index() function. This function returns the index of the first occurrence of the element inside the tuple. If the element is not present, it raises an error.
# create a tuple t = (2, 7, 5, 1, 4) # find min value min_val = min(t) # display its index print(t.index(min_val))
We get the index of the min value as 3.
Get min value using iteration
Alternatively, you can iterate through each value in the tuple and keep track of the minimum value to find the min value in the tuple. You can use an additional variable to keep track of the index of the minimum value.
Let’s look at an example.
# create a tuple t = (2, 7, 5, 1, 4) # find min value using loop min_val = t min_val_idx = 0 for i in range(len(t)): if t[i] < min_val: min_val = t[i] min_val_idx = i # display the min value print(min_val) # display its index print(min_val_idx)
We get the minimum value and its index in the tuple.
Note that if your tuple contains more than one occurrence of a value, the
index() function will only return its first occurrence. To get all the indexes of occurrence, you iterate through the elements in a list comprehension.
# create a tuple t = (1, 7, 5, 1, 7) # get all indexes of 1 idx = [i for i in range(len(t)) if t[i] == 1] print(idx)
We get all the indexes of occurrence for the value
1 in the tuple
You might also be interested in –
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.