Python Forum

Full Version: Find the highest value of a list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I'm trying to build a small program to find the highest value of a list. I tried this :

def nb_max(L):
    maxi = L[0]
    for x in [0,len(L)-1]:
        if maxi<=L[x]:
               maxi=L[x]
        else :
            pass
    return maxi
But it doesn't work. I can't understand why....

Any idea ?

Thank you Smile
When you write for x in [0, len(L)-1], x takes only two values: 0 and len(L)-1.

Also note that such a function already exists in Python, max(L) returns the highest value of L.
(Oct-29-2021, 10:25 AM)Menthix Wrote: [ -> ]Hello,
I'm trying to build a small program to find the highest value of a list. I tried this :

def nb_max(L):
    maxi = L[0]
    for x in [0,len(L)-1]:
        if maxi<=L[x]:
               maxi=L[x]
        else :
            pass
    return maxi
But it doesn't work. I can't understand why....

Any idea ?

Thank you Smile

Hello,

I am only at page 30 of the Python book I am working through so I don't know what def and return do.
I rewrote your code using syntax I could understand and it seems to work OK:

andrew@ASUS-Laptop:~/Python$ cat prog22.py
L = [1, 2, 3]
maxi = L[0]
for x in [0,len(L)-1]:
if maxi<=L[x]:
maxi=L[x]
else :
pass
print (maxi)
andrew@ASUS-Laptop:~/Python$ python prog22.py
3
andrew@ASUS-Laptop:~/Python$

Are you sure your list was populated at the start?
If you want to make your own max function rather than use the built-in max, for practice/homework/whatever.
Use a better name than L for the list using numbers seems more suitable.
Also you may as well name maxi maximum.
Iterate directly over the numbers in the for loop, as maximum has already been defined as the first item, the rest can be iterated by using:
for number in numbers[1:]:.
The if statement only needs to check if maximum is lower than number, not less than or equal to.
The else part of the if statement is not required
(Oct-29-2021, 10:38 AM)Gribouillis Wrote: [ -> ]When you write for x in [0, len(L)-1], x takes only two values: 0 and len(L)-1.

Thank you, the issue definitly came from here !
Works better now.