-2

Hi I am a beginner in Python, and I am trying to make a function which shows me the largest element in the list. Where I am going wrong?

l = [2,6,9,7,41,4]

def getmax(l):
    assume = l[0]
    for i in range(1,len(l)):
        if l[0] > l[i]:
            assume = l[0]
        else:
            assume = l[i]
    return assume

print(getmax(l))
John Paul
  • 13
  • 4
  • 3
    You shouldn't use `l[0]` in the `if` and `assume = l[0]`. This way you're always comparing/setting against the first index. Anyway, why not just use the [`max`](https://stackoverflow.com/questions/6193498/pythonic-way-to-find-maximum-value-and-its-index-in-a-list) function? – 0stone0 Mar 17 '22 at 15:44
  • 1
    What evidence do you have that you are doing anything wrong, and why won't you share? – Scott Hunter Mar 17 '22 at 15:45
  • @0stone0 thanks a lot man!! I feel so dumb now :') – John Paul Mar 17 '22 at 15:46
  • 1
    Does this answer your question? [Python: Function returning highest value in list without max()?](https://stackoverflow.com/q/19469136/6045800) – Tomerikoo Mar 17 '22 at 15:52

2 Answers2

3

This is what you want, I believe:

l = [2,6,9,7,41,4]

def getmax(l):
    assume = l[0]
    for i in range(1,len(l)):
        if l[i] > assume:
            assume = l[i]
    return assume

print(getmax(l))

Output:

41
constantstranger
  • 9,176
  • 2
  • 5
  • 19
0

hey of course you can use the builtin max function, but that won't be perfect for the purpose.

Your problem is that you always compare against the l[0] element instead of "assume" :).

def getmax(l: list) -> int:
    assume = l[0]
    for number in l[1:]
         if number > assume:
             assume = number
    return assume

As you see, you don't need the else branch, as the number stays the same with same numbers or a lower number :).

The l[1:] might be confusing, but it means: Take everythin from iterable "l" but skip until the first element.

loki.dev
  • 172
  • 6
  • 1
    *"Take everythin from iterable "l" but skip until the first element."* - that is actually confusing... I think it simply means take everything from the second element to the end – Tomerikoo Mar 17 '22 at 15:50
  • `l[1:]` actually means "create a copy of `l` omitting the first element". It does not just skip the first element in iteration. – khelwood Mar 17 '22 at 15:51
  • Hi @loki.dev can you explain me a bit about this line `(l: list) -> int:`? – John Paul Mar 17 '22 at 21:24
  • Hey @JohnPaul - Yes. This is optional typing. It is there to make sure we now what each of these variables contain. With tools like mypy you can check that everything works as intended :) – loki.dev Mar 18 '22 at 16:14