Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the maximum number in a list using a loop?

So I have this list and variables:

nums = [14, 8, 9, 16, 3, 11, 5]

big = nums[0]

spot = 0

I'm confused about how to actually do it. I want to use this exercise to give me a starter. How do I do that on Python?

like image 489
user1998529 Avatar asked Jan 21 '13 22:01

user1998529


2 Answers

Usually, you could just use

max(nums)

If you explicitly want to use a loop, try:

max_value = None
for n in nums:
    if n > max_value: max_value = n
like image 164
helmbert Avatar answered Sep 21 '22 19:09

helmbert


Here you go...

nums = [14, 8, 9, 16, 3, 11, 5]

big = max(nums)
spot = nums.index(big)

This would be the Pythonic way of achieving this. If you want to use a loop, then loop with the current max value and check if each element is larger, and if so, assign to the current max.

like image 38
alex Avatar answered Sep 20 '22 19:09

alex