In this post, we will understand how to get the index of the elements in a python list that are the largest and smallest.
1. Naive approach
This uses more memory and compares every element with every other element. The largest and the smallest elements are found first and then their index.
Time for an example:
my_list = [7, 11, 89, 0, 34, 67]
min_pos = my_list[0]
for i in my_list:
if min_pos >= i:
min_ele = i
min_index = my_list.index(i)
elif min_pos < i:
max_ele = i
max_index = my_list.index(i)
print("Element " + str(min_ele) + " is at position " + str(min_index))
print("Element " + str(max_ele)+ " is at position " + str(max_index))
Output:
Element 0 is at position 3
Element 67 is at position 5
2. Using the index function
A better way is to use the index function to get the index position of the largest and the smallest element in the list and assign it to relevantly named variables.
Time for an example:
def minimum(my_list, n):
max_pos = my_list.index(max(my_list))
min_pos = my_list.index(min(my_list))
print("The maximum is at position", max_pos + 1)
print("The minimum is at position", min_pos + 1)
my_list = [7, 11, 89, 0, 34, 67, 89]
minimum(my_list, len(my_list))
Output:
The maximum is at position 3
The minimum is at position 4
Conclusion
In this post, we understood how to get the position of the largest and the smallest element in a list of integers. Let us know how you would approach this problem in the comment section below.
You may also like: