Monday, July 26, 2021

Stack Abuse: Python: Get Max Element of List, Dictionary or Tuple

Introduction

In this guide, we'll take a look at how to find the maximum element of a few common data structures in Python, such as a list, dictionary, and tuple.

The max() method, built into the Python namespace works wonders here for built-in types.

How to Get the Max Element of a Python List

A list is Pythons' built-in type that is used to sequentially store multiple references in a single object in memory.

When compared to the other programming languages, a Python list is essentially a simple array. Elements are indexed based on their position in the list and there can be multiple elements with the same value.

The main difference is that lists in Python can contain elements of different types. They're heterogenous.

# List of different type elements 
example_list = ["string", 5, "five", 4, "4"]

Note: If elements are not comparable via the comparison operators (<,>,==,!=), the max() function won't work. Thus, we'll want to ensure that a list is homogenous before attempting to find the maximum element.

As long as you can compare the elements properly, you can find the maximum element regardless of type. Most of the time, you'll be working with integers:

integer_list = [24, 9, 20, 17, 201, 16, 7]

The easiest way to get the max element of a list is to use the built-in max() method:

max_element = max(integer_list)
print("Max element of a list: ", max_element)

This code will have the expected output:

Max element: 201

You can also compare strings lexicographically, and find the lexicographically greatest string in a list via the max() function:

string_list = ["string", "five",  "4"]
max_element = max(string_list)

print("Max element:", max_element)

This results in:

Max element: string

Another way to find the max element of a list is to sort it using the sort() method, and then get the last element of the sorted list, because the sort() method sorts list in an ascending order:

integer_list = [24, 9, 20, 17, 201, 16, 7]
integer_list.sort()
# myList = [7, 9, 16, 17, 20, 24, 201]
max_element = integer_list[-1]

print("Max element of a list: ", max_element)

This code will also have the same output as the previous:

Max element of a list: 201

If we'd like to also find the index of the max element, the easiest way is to use the built-in index() method:

integer_list = [24, 9, 20, 17, 201, 16, 7]

max_element = max(integer_list)
max_element_index = integer_list.index(max_element)

print("Max element of a list: ", max_element, " at index: ", max_element_index)

Which will output:

Max element of a list:  201  at index:  4

How to Get the Max Element of a Python Dictionary

Dictionaries in Python are used to store key-value pairs. Pairs with the same key are not allowed and, since Python 3.7, pairs in a dictionary are considered to be ordered.

Dictionaries are defined with the list of key-value pairs between a pair of curly brackets:

dictionary = {
    "key24": 24, 
    "key7": 9,
    "key20": 201,
    "key17": 17, 
    "key201": 201, 
}

The easiest way to retrieve the value of the max element of a dictionary is also to use the built-in max() method, with the list of values passed as the argument:

max_element = max(dictionary.values())
print("Max element of a dict: ", max_element)

This boils down to the previous method, since the values() method returns the values stored in a list. This will give the correct output:

Max element of a dict: 201

If we want to find the key of the first element with the max value as well, the easiest way is to use the max() method supplying the dictionary and retrieving the element via dictionary.get().

max_val = max(dictionary.values())
max_val_key = max(dictionary, key=dictionary.get)

print("Max element of a dict:", max_val, "with the key:", max_val_key)

This will output the value of the max element and the first matching key:

Max element of a dict: 201 with the key: key20

Note: You might be tempted to use max(dictionary) to find the key with the maximum value. However, this approach will return the maximum key itself. In our case, it would return the key with the maximum lexicographical value in the dictionary.

How to Get the Max Element of a Tuple

A tuple is Pythons' built-in type sequentially store references to multiple objects in memory. They're in many ways similar to lists, and the most notable difference between the two of them is that a tuple is an immutable data structure, unlike a list.

They're commonly used to store only a few results, typically as function return types.

In Python, we define tuples using a pair of brackets:

# Tuple of different element types 
exampleTuple = ("string", 5, "five", 4, "4")

In much the same way how comparison in lists works, you can only run the max() method on compatible data types:

int_tuple = (24, 9, 20, 17, 201, 16, 7)
string_tuple = ('one', 'two', 'three')

Probably the easiest way to get the max element of a tuple is to use the built-in max() method:

int_tuple = (24, 9, 20, 17, 201, 16, 7)
string_tuple = ('one', 'two', 'three')

max_int = max(int_tuple)
print("Max element of a tuple: ", max_int)

max_str = max(string_tuple)
print("Max element of a tuple: ", max_str)

Again, this results in the greatest integer, and lexicographically greatest string:

Max element of a tuple:  201
Max element of a tuple:  two

Conclusion

Finding the max element of a data structure is a pretty common task. All standard data structures in Python have a similar way of finding the max element - relying on the max() method for all collections.

In this guide, we've covered how to find the max element of a few most popular data structures in Python, while taking into consideration the special features of each of them.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...