There are many methods to find the largest number in a list in python. In this tutorial, you will learn how to find the largest number in a list in python using various methods.
Methods to find the largest number in a list of python
Let’s know all the methods to find the largest number in a list.
Method 1: Using the max() function
You can use the max() function to find the largest number in a list.
my_list = [100, 200, 300, 400, 500]
largest_num = max(my_list)
print(largest_num)
Output
500
The list my_list contains integers and the max() function is used to identify the biggest number. The largest integer in the list is stored in the variable called largest_num, which is then printed to the console.
Method 2: Sorting and selecting the element
The second method is to first sort the elements of the list in descending order and then select the first elements of the list. It will be the highest element of the list.
Use the below lines of code to find it.
my_list = [100, 200, 300, 400, 500]
my_list.sort(reverse=True)
largest_num = my_list[0]
print(largest_num)
Output
500
In the above code, we first sorted the my_list of integers in descending order by using the sort() method with the argument reverse=True. Then, the largest number in the list is assigned to the variable largest_num, which is then printed out to the console.
Method 3: Find the largest number in a list python using for loop
The third method you will use is the for a loop. We set largest_num to the first item in the list. Using a for loop, we go through each element in the list and compare it to largest_num. If the current element is bigger, we make it the new largest_num. After the loop has been complete, largest_num contains the largest number from the list.
Execute the below lines of code to find the largest number.
my_list = [100, 200, 300, 400, 500]
largest_num = my_list[0]
for num in my_list:
if num > largest_num:
largest_num = num
print(largest_num)
Output
500
Conclusion
There are certain cases when you have to find the max of the elements of a list. Like normalization etc. The above three approaches will provide the same result. Using the max() function is the simplest and clearest way. If the list is very long and then use the sort() function to find the biggest number. Lastly, If you need to do further operations with the elements in the list, the loop is the best way to go.
Leave a Reply