Technology3 min read

Find the Position of the Largest and the Smallest Element in Python List

Abhishek Ahlawat

By Abhishek Ahlawat โ€” Recently

Founder of StudyTonight and a MERN fullstack developer. Writes about JavaScript, web development, Linux, and tech.

#Python#Python List

Summarize this article using AI

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:

Spotted something outdated or wrong?

Liked this? See more StudyTonight posts in Google results.

Add StudyTonight as a preferred source
Next questLIVE OPSStep 2 / 3

Practice real incidents in the browser

System Design Ops โ€” put out fires, ship fixes, and stack XP. Reading done. Time to play.

Play System Design
  • +XP

    Every sim

  • Incidents

    Live ops

  • Ranks

    Climb up

Read next