Python Forum
Find the highest value of a list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Find the highest value of a list (/thread-35404.html)



Find the highest value of a list - Menthix - Oct-29-2021

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


RE: Find the highest value of a list - Gribouillis - Oct-29-2021

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.


RE: Find the highest value of a list - Andrew_Reid - Oct-29-2021

(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?


RE: Find the highest value of a list - Yoriz - Oct-29-2021

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


RE: Find the highest value of a list - Menthix - Oct-29-2021

(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.