743
In this example we show you 2 examples of finding the smallest and largest numbers in a list
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