Python program to find the maximum and minimum element in a list

Python program to find the maximum and minimum element in a list :

In this tutorial, we will learn how to find the maximum and minimum number in a python list. All the numbers will be entered by the user. First, we will ask the user the total number he wants to enter. Then using a for loop, we will read each number and append to the list. Finally, again using one more for loop, we will calculate the maximum and minimum number and print out the result. Let’s take a look into the program first :

Python Program :

#1
my_list = []

#2
count = int(input("How many numbers you want to add : "))

#3
for i in range(1,count+1):
	my_list.append(int(input("Enter number {} : ".format(i))))

#4
print("Input Numbers : ")
print(my_list)

#5
min = my_list[0]
max = my_list[0]

#6
for no in my_list:
	if no < min : min = no elif no > max :
		max = no

#7
print("Minimum number : {}, Maximum number : {}".format(min,max))

Explanation :

The commented numbers in the above program denotes the step number below :

1. Create one empty list my_list.
2. Get the total number of elements user is going to enter and save it in count variable.
3. Using a for loop, get the numbers and append it to the list my_list.
4. Print the list to the user.
5. Create two variables to hold the minimum and maximum number. We are assigning the first element of the list to both of these variables first. We will update these variables on next step.
6. Run one for loop on the list again. For each number, check if it is less than the minimum number. If yes, assign the minimum value holding variable to this number. Similarly, update the maximum value if the number is more than current maximum.
7. After the list is completed reading, print out both maximum and minimum numbers.

Sample Output :

How many numbers you want to add : 4
Enter number 1 : 1
Enter number 2 : 2
Enter number 3 : 3
Enter number 4 : 4
Input Numbers :
[1, 2, 3, 4]
Minimum number : 1, Maximum number : 4
How many numbers you want to add : 5
Enter number 1 : 77
Enter number 2 : 12
Enter number 3 : 134
Enter number 4 : 42
Enter number 5 : 3
Input Numbers :
[77, 12, 134, 42, 3]
Minimum number : 3, Maximum number : 134
How many numbers you want to add : 3
Enter number 1 : 100
Enter number 2 : 1221
Enter number 3 : 12
Input Numbers :
[100, 1221, 12]
Minimum number : 12, Maximum number : 1221

Leave a Reply