In Python, working with lists is a common task. Sometimes, we need to find the largest number in a list. This can be useful in a variety of applications, from data analysis to simple programming tasks. In this tutorial, we will explore different methods to find the biggest number in a list in Python. By the end of this tutorial, you will have a solid understanding of how to find the maximum value in a list and be able to apply this knowledge to your own Python projects.
Methods to find the biggest number in a list in Python
There are multiple methods using which you can get the maximum value in a Python list. Let’s look at these methods in detail with the help of some examples.
1) Using the max()
function
max()
is a built-in function in Python that returns the largest item in an iterable or the largest of two or more arguments. To get the biggest number in a list, pass the list as an argument to the max()
function.
Let’s look at an example.
# create a list ls = [3, 5, 1, 9, 2] # find the biggest value in the list biggest_num = max(ls) print(biggest_num)
Output:
Highlighted programs for you
Flatiron School
Flatiron School
University of Maryland Global Campus
University of Maryland Global Campus
Creighton University
Creighton University
9
We get the maximum value in the list as 9, which is the correct answer.
2) By iterating through the list
In this method, we iterate through the list and keep track of the biggest value encountered in a separate variable. After we have gone through the entire list, the variable will have the biggest value in the list.
# create a list ls = [3, 5, 1, 9, 2] # find the biggest value in the list if ls: biggest_num = ls[0] for val in ls[1:]: if val > biggest_num: biggest_num = val print(biggest_num) else: print("list is empty")
Output:
9
You can see that we get 9 as the biggest value in the list, which is the correct answer.
3) Sort the list
The idea here is to sort the list in ascending order and get the last element in the list. In a sorted list, the largest number will be at the end of the list. You can use the built-in sorted()
function to sort a list in Python, it returns a new list that is sorted.
# create a list ls = [3, 5, 1, 9, 2] # sort the list ls_sorted = sorted(ls) # find the biggest value print(ls_sorted[-1])
Output:
9
We get the biggest value in the last as 9, which is the correct answer.
Conclusion
In this tutorial, we looked at how to get the biggest number in a Python list using different methods. Using the max()
is the simplest and the recommended way to get the largest value in a list. The other methods, while being correct, are not as straightforward as the max()
function.
You might also be interested in –