In this lesson we will look for the maximum value of a list in Python either by using the Python max() function, or by building our own algorithm.
Exercise – Python max()
Populate a list with 20 numbers of your choice. After entering, view all the elements of the list with their index.
Then find the maximum value among those entered in the list.
First method with Python max()
In this first method, we populate a list of numbers. Next we simply use the max () function to determine the maximum of the list.
Here is the code:
number = [13, 22, 18, 3, 1, 9]
n_max = max(number);
print("The largest number is:", n_max)
Second method without Python max()
In this second method we will create a custom algorithm.
First we initialize the list of name numbers to the empty list. Then we insert as input 20 numbers of your choice in the list and display them using another for loop.
Take care to view the elements with their index using another for loop, as you are asked to view the list after entering the numbers.
N.B. The entered values can be both positive and negative.
So the numbers can also be all negative, for example. This is why the intuition of setting the maximum to zero is wrong.
In this regard, let’s make an example by setting maximum = 0
And we put the numbers in the list:
-5, -12, -1, -8, -15
At the end, the maximum value will be 0, as the comparisons made did not allow to replace this value.
This is clearly a mistake!
Then we need to initialize the maximum value to the first element of the list and then with a for loop we compare the other elements with the maximum value.
If the found element is greater than the maximum value then it is replaced, otherwise the maximum will be the first element in the list.
Here is the code:
n = 5
numbers = []
for i in range(n):
number = int(input('Insert a number: '))
numbers.append(number)
n_max = numbers[0]
for i in range(n):
if numbers[i] > n_max:
n_max = numbers[i]
print('The largest number is: ', n_max)
In this last example we did not use the Python max() function
Useful links
1 – Introduzione al linguaggio Python