Python program: Largest and smallest in a list
Find the largest and smallest numbers in a list, with a loop and with max/min.
The code
nums = [34, 7, 23, 32, 5, 62, 14] biggest = smallest = nums[0] for n in nums[1:]: if n > biggest: biggest = n if n < smallest: smallest = n print(biggest, smallest) print(max(nums), min(nums))
Output
62 5 62 5
How it works
Start from the first item and update as you go. Starting from 0 would be a bug for lists of negative numbers.
Python features used
Learn the ideas behind it in the free lesson Loops.