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 am confused about how to actually do this. Please help! I am new to Python and I want to use this exercise to give me a starter. I want to start with "repeated list length", for example, in Scratch or BYOB, but how to do it in Python?

+4
source share
7 answers

You can usually 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 
+13
source
 nums = [14, 8, 9, 16, 3, 11, 5] big = None spot = None for i, v in enumerate(nums): if big is None or v > big: big = v spot = i 
+9
source

Here you go ...

 nums = [14, 8, 9, 16, 3, 11, 5] big = max(nums) spot = nums.index(big) 

That would be a 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 the current max.

+8
source

Why not just use the built-in max () function:

 >>> m = max(nums) 
By the way, some answers to such questions may be useful:
+1
source

To solve the second question, you can use the for loop:

 for i in range(len(list)): # do whatever 

You should notice that range() can have 3 arguments: start , end and step . The beginning is the number from which to start (if not specified, it is 0); start is inclusive. The end is the end to be put on (this must be given); end is exclusive: if you do range(100) it will give you 0-99. A step is also optional, which means which interval to use. If the step is not specified, it will be 1. For example:

 >>> x = range(10, 100, 5) # start at 10, end at 101, and use an interval of 5 >>> x [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95] # note that it does not hit 100 

Since end is exceptional, to include 100, we could do:

 >>> x = range(10, 101, 5) # start at 10, end at 101, and use an interval of 5 >>> x [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100] # note that it does hit 100 
+1
source

Python already has a built-in function for such a requirement.

 list = [3,8,2,9] max_number = max(list) print max_number # it will print 9 as big number 

however, if you find the maximum number with classic vay, you can use loops.

 list = [3,8,2,9] current_max_number = list[0] for number in list: if number>current_max_number: current_max_number = number print current_max_number #it will display 9 as big number 
0
source
 scores = [12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 31, 31, 37, 56, 75, 23, 565] # initialize highest to zero highest = 0 for mark in scores: if highest < mark: highest = mark print(mark) 
0
source

All Articles