1

I have been trying to find the maximum element in a list using a simple program

print ("Enter the elements of array seperated by spaces : ")
t = str(raw_input())
arr = list()
arr = map(long,t.split(' '))
print arr
print max(arr)
for i in arr:
    m=arr[0]
    if i>m:
        m=i
print ("The largest element in arary is : "+str(m))

The input that I passed in was :

1 2 3 4 5 23682967 4574 433

And the expected answer for the same should be 23682967

which is what I'm able to get using the inbuilt function of python called max()

but not from the code that I've written,

The output that my code gives is : 433

Can someone please guide me in understanding this behavior of python ?

3
  • 4
    m=arr[0] should be outside the for loop Commented Aug 22, 2015 at 14:36
  • 1
    Anand's answer is great. Nothing to add on that. But I wanted to give three points of feedback on your code. Hopefully you learn something from it. (1) raw_input already returns a string, so no need to use str on it. (2) raw_input supports giving a prompt, so no need to use print before. (3) The first assignment of arr does nothing, because you reassign it in the next statement. You can just remove that line. Commented Aug 22, 2015 at 17:23
  • @agtoever Thanks for these points, All of them noted, they would surely improve my coding skills in future programs. Thanks for your suggestions :) Commented Aug 23, 2015 at 2:12

1 Answer 1

4

The issue occurs because of the following line inside your for loop -

m=arr[0]

It causes i to be checked against the first element in the array always causing your loop solution to return the last element that is bigger than the first element in the array which in your case is 433.

You should have that line before the for loop. Example -

m=arr[0]
for i in arr:
    if i>m:
        m=i
Sign up to request clarification or add additional context in comments.

1 Comment

Yup, It's working now, Thanks Anand for such a quick and wonderful explanation over the behavior :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.