How to find the maximum and minimum values in a list using Python?
How to find the maximum and minimum values in a list using Python?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
05-Jul-2023Sure, there are a few ways to find the maximum and minimum values in a list using Python. Here are a few examples:
Using the
max()
andmin()
functions:The
max()
andmin()
functions are built-in functions in Python that can be used to find the maximum and minimum values in a list. Themax()
function takes a list as input and returns the largest value in the list. Themin()
function takes a list as input and returns the smallest value in the list.For example, the following code will find the maximum and minimum values in the list
list1
:Python
The output of the code is:
Code snippet
Using a for loop:
You can also use a for loop to find the maximum and minimum values in a list. The basic idea is to iterate over the list, keeping track of the largest and smallest values that you have seen so far.
For example, the following code will find the maximum and minimum values in the list
list1
:Python
The output of the code is the same as the previous example.
Using the
enumerate()
function:The
enumerate()
function in Python can be used to iterate over a list and get the index of each element. This can be useful for finding the maximum and minimum values in a list, because you can use the index to keep track of which element is the largest and smallest so far.For example, the following code will find the maximum and minimum values in the list
list1
:Python
The output of the code is the same as the previous two examples.