-4

I am trying to find the largest number in the list using Python but I am getting an index out of range error. Can anybody help ?

numbers = [12, 33, 44, 55, 11, 19, 98, 17, 12]
largest = 0
for index in numbers:
    if largest < numbers[index]:
        largest = numbers[index]
print(largest)
1
  • 2
    So why didn't you want to use: print(max(numbers))? Commented Aug 21, 2022 at 14:15

2 Answers 2

1

When you iterate a list using for i in lst the i is the value not the index, so in your case, it will be like below example. BTW: I guess you need to learn some basics of python list iteration. See: https://favtutor.com/blogs/python-iterate-through-list.

Note: I just edited the largest variable using numbers[0] otherwise your program will not able to find the max value when you have negative values in the list.

numbers = [12, 33, 44, 55, 11, 19, 98, 17, 12] 
largest = numbers[0]   # take first element as max    
for value in numbers: 
    if largest < value: 
        largest = value
print(largest)

OR with single line python max()

largest = max(numbers)

Working Code: https://rextester.com/CLBM63548

Sign up to request clarification or add additional context in comments.

Comments

0

you can use max(numbers) to find the maximum number

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.