Python

Find Max Value in List Python

None of us can dispute that Python is one of the most popular and useful programming languages. It offers a wide range of data types that are useful in a wide range of applications.

One of the fundamental and versatile data types in Python is a list. A Python list is a collection of ordered items separated by commas. A python list is mutable, and you can change list items.

This tutorial will show you how to create a python list and offer various ways to locate the maximum value inside a list.

How to Create a Python List

Let us start with the basics: how to create a list.

NOTE: If you are already familiar with python lists creation, feel free to skip ahead.

To create a list in Python, we add all the items (separate each item with a comma) inside a pair of square brackets []

Items in a Python list can support various data types, including string, integers, floats, dictionaries, and even nested lists.

The following example creates a list called my_list with various items in it.

# initialize an empty list
my_list = []
# list with integers, strings, floats, dictionaries and nested lists
my_list_ = [10, "Hello World", 10.1, ["nested_list", {"key": "value"}, 10]]

In the first list, we initialize a list with no items. Next, we populate it with various data types including integers, strings, floats, dictionaries, and lists.

How to Access List Items

We can access items in a list using various methods. For simplicity, we will only discuss two methods.

The first one:

1: Array Indexing

To access items in an array using the array indexing approach, we use the index operator in Python. Inside the operator, we pass the index we wish to access.

NOTE: Indexing in Python starts at the index of 0. That means the first item in a list is always index 0.

Consider the example below:

db = [
"MySQL",
"PostgreSQL",
"SQLite",
"MongoDB",
"MariaDB",
"Redis",
"Microsoft SQL server",
"Oracle",
"Firebase",
"Elasticsearch"
]

Let us assume the list above contains the most popular databases. To find the most used database, we can use the syntax:

print(db[0])

The statement above should return MySQL.

NOTE: Accessing items out of the list index will result in an Index Error. For example, the db list contains 10 items. That means the index of the 10th item is 10 – 1 since the index starts at 0.

If we try to access the 10th index, we get an error:

print(db[10])

IndexError: list index out of range

The above method is useful when you know how many items are on the list. If you are not sure of the items in the list, you can use the second method.

2: Using a Loop

A simple method to access all the items in a list is to use a simple for loop. An example code for that is below:

db = [

"MySQL",

"PostgreSQ;",

"SQLite",

"MongoDB",

"MariaDB",

"Redis",

"Microsoft SQL server",

"Oracle",

"Firebase",

"Elasticsearch"

]

for item in db:

print(item)

This will loop each item in the db list and print out every item in it.

An example output for that is:

MySQL

PostgreSQ;

SQLite

MongoDB

MariaDB

Redis

Microsoft SQL server

Oracle

Firebase

Elasticsearch

How to Find Max Value in a Python List

Now, let us dive into this article’s essence; how to find the maximum value in a list. For this one, we will implement various methods to attain the same result.

1: Using the sort method

The first method we can use to find the maximum value in a Python list is the sort method.

To do this, we pass the list’s name to the sort() method, which will sort all the values in ascending order. After the list sorting process, we can access the last item in the array to get the largest value.

For example, consider the array of values below:

values = [

10, 29.34, 23, 72, 110, 773, 322, 63, 1, 34, 5, 10, 64.3

]

We can simply call the sort method against the list above and get the last item.

To get the last item in an array, we can use the indexing option and specify the index as -1, which is the last item.

Consider the example code below:

values = [

10, 23, 72, 110, 773, 322, 63, 1, 34, 5, 10

]

values.sort()

print(f"The maximum value in the list is: {values[-1]}")

Once we run the code above, we should get the maximum value as:

The maximum value in the list is: 773

2: Using If…else

Another simple way to get the maximum value in a list is to use a simple if…else statement.

To implement this, we first assume that the largest value is the first item in the index. Next, we loop through each item in the list and check if it is larger than the initial value. Hence, it is set as the max value; otherwise, move to the next one.

Consider the implementation below:

values = [

10, 23, 72, 110, 773, 322, 63, 1, 34, 5, 10

]

# assume maximum value is at index 0

maximum = values[0]

for i in values:

if i > maximum:

maximum = i

print(f"The maximum value is: {maximum}")

Similarly, if we run the above code, we should get the maximum value of 773. Here is an example output:

The maximum value is: 773

3: Using the Max function

Python has an in-built max function that you can use to locate the maximum value in an iterable. For example, if we call the max function in a list of strings, it returns the last item with the strings arranged in alphabetical order.

Here is an example:

values = [

10, 23, 72, 110, 773, 322, 63, 1, 34, 5, 10

]

print(f"The maximum value is: {max(values)}")

4: Using Heap Queue Nlargest Method

An unconventional way to find the largest value in the list is to use the nlargest method in the Heap Queue module.

This module implements a heap queue algorithm. Learn more about the Python heap queue module.

The nlargest method will return the largest values specified. For example, if you specify 5, the method will return the 5 largest values in the iterable specified.

For example:

from typing import ValuesView

import heapq

values = [

10, 23, 72, 110, 773, 322, 63, 1, 34, 5, 10

]

print(f"The maximum value is {heapq.nlargest(1, values)}")

The code above should return the value as 773.

The maximum value is: 773

To show the 5 largest values, set the number of items to 5 as:

from typing import ValuesView

import heapq

values = [

10, 23, 72, 110, 773, 322, 63, 1, 34, 5, 10

]

print(f"The maximum values in order are {heapq.nlargest(5, values)}")

This should return an output similar to the one shown below:

The maximum values in order are [773, 322, 110, 72, 63]

Although the above method can be overkill, you might find it useful in some instances.

Conclusion

This tutorial has shown you how to create python lists, access items in a list, and various ways to get the maximum values in a Python list.

Thank you for reading!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list