Home » Find The Largest and Smallest Number in a List in python

Find The Largest and Smallest Number in a List in python

Oracle Java Certification
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Programmer II [1Z0-816] Practice Tests
1 Year Subscription
Spring Framework Basics Video Course
Java SE 11 Developer (Upgrade) [1Z0-817]

In  this example we show you 2 examples of finding the smallest and largest numbers in a list

Table of Contents

Example 1

In this example we use the min and max functions in to return the minimum and maximum values in a List.

NumberList = []
Number = int(input("Please enter the Total Number of Elements: "))
for i in range(1, Number + 1):
    value = int(input("Please enter the Value of %d Element : " %i))
    NumberList.append(value)

print("The Smallest Element in the List is : ", min(NumberList))
print("The Largest Element in the List is : ", max(NumberList))

You will see the following

>>> %Run smalllargelist1.py
Please enter the Total Number of Elements: 5
Please enter the Value of 1 Element : 11
Please enter the Value of 2 Element : 24
Please enter the Value of 3 Element : 12
Please enter the Value of 4 Element : 65
Please enter the Value of 5 Element : 2
The Smallest Element in the List is :  2
The Largest Element in the List is :  65

Example 2

In this example we use the sort function to sort List elements in ascending order.

We then use the index

NumberList = []
Number = int(input("Please enter the Total Number of Elements: "))
for i in range(1, Number + 1):
    value = int(input("Please enter the Value of %d Element : " %i))
    NumberList.append(value)

NumberList.sort()

print("The Smallest Element in the List is : ", NumberList[0])
print("The Largest Element in the List is : ", NumberList[Number - 1])

You will see the following

>>> %Run smalllargelist2.py
Please enter the Total Number of Elements: 5
Please enter the Value of 1 Element : 11
Please enter the Value of 2 Element : 24
Please enter the Value of 3 Element : 12
Please enter the Value of 4 Element : 65
Please enter the Value of 5 Element : 2
The Smallest Element in the List is :  2
The Largest Element in the List is :  65

Link

This is in our github repository

https://github.com/programmershelp/maxpython/tree/main/code%20example/List%20examples

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More