Python Program to Find Largest Number in List
You can find the largest number in a list using the built-in
max() function like this: largest = max(your_list).Examples
Input[3, 5, 1, 9, 2]
Output9
Input[-10, -5, -3, -1]
Output-1
Input[7]
Output7
How to Think About It
To find the largest number in a list, you look at each number one by one and remember the biggest number you have seen so far. At the end, the number you remembered is the largest.
Algorithm
1
Start with the first number as the largest.2
Look at each number in the list one by one.3
If you find a number bigger than the current largest, update the largest number.4
After checking all numbers, return the largest number.Code
python
numbers = [3, 5, 1, 9, 2] largest = max(numbers) print(largest)
Output
9
Dry Run
Let's trace the list [3, 5, 1, 9, 2] through the code using the max function.
1
Start with the list
numbers = [3, 5, 1, 9, 2]
2
Find the largest using max()
max(numbers) returns 9
3
Print the largest number
print(9) outputs 9
| Number | Current Largest |
|---|---|
| 3 | 3 |
| 5 | 5 |
| 1 | 5 |
| 9 | 9 |
| 2 | 9 |
Why This Works
Step 1: Using max() function
The max() function automatically checks all numbers in the list and returns the biggest one.
Step 2: Storing the result
We store the largest number found in the variable largest to use or print later.
Step 3: Output the largest number
Printing largest shows the biggest number from the list on the screen.
Alternative Approaches
Manual loop to find largest
python
numbers = [3, 5, 1, 9, 2] largest = numbers[0] for num in numbers: if num > largest: largest = num print(largest)
This method shows how to find the largest number without using built-in functions, useful for learning the logic.
Using sorted() function
python
numbers = [3, 5, 1, 9, 2] largest = sorted(numbers)[-1] print(largest)
Sorting the list and picking the last element also gives the largest number but is less efficient than max().
Complexity: O(n) time, O(1) space
Time Complexity
The program checks each number once, so the time grows linearly with the list size, making it O(n).
Space Complexity
It uses only a few extra variables regardless of list size, so space complexity is O(1).
Which Approach is Fastest?
Using max() is fastest and simplest; manual loops are educational but longer; sorting is slower due to O(n log n) time.
| Approach | Time | Space | Best For |
|---|---|---|---|
| max() function | O(n) | O(1) | Quick and simple largest number search |
| Manual loop | O(n) | O(1) | Learning how to find max without built-ins |
| sorted() function | O(n log n) | O(n) | When you also need sorted data |
Use
max() for a simple and fast way to find the largest number in a list.Beginners sometimes forget to handle empty lists, which causes errors when using
max().