I have the following python code in which I have to get the largest number from the list without using the max function I have taken the code from the internet but it lacks an explanation so I would like someone to explain it to me
lista = [3, 7, 23, -2, 0, 6]
#Declaramos la variable max que sea igual a 0
max = lista[0]
#No se que hace este bucle exactamente
for lista in lista:
if lista > max:
max = lista
print("El máximo es " + str(max))
Assigns the value at index 0 of the array to the variable max, that is
max = 3
Iterates and checks if the element is greater than the current element, if so it sets the variable equal.
visual example
first iteration
second iteration
third iteration
fourth iteration
fifth iteration
sixth iteration
There are no more iterations, it leaves the
for
andmax
is still valid23
GRADES:
max = lista[0]
does not assignmax = 0
as the comment says, but to index 0 of your listAlthough the code works well, do not use the same name of the variable in the for, that is, if you
list
call itlista
in the for, do not do thisfor lista in lista
since it is confusing and can cause problems when using it again,lista
that is why in the example i changed the name toelemento