Get maximum list python

Find Maximum Value in List in Python

In this article, we will learn to find the maximum value in a list in Python. We will use some built-in functions, simple approaches, and some custom codes as well to understand the logic. Let’s first have a quick look over what is a list in Python and how can we find the maximum value or largest number in a list.

Python List

Python has a built-in data type called list. It is like a collection of arrays with different methodology. Data inside the list can be of any type say, integer, string or a float value, or even a list type. The list uses comma-separated values within square brackets to store data. Lists can be defined using any variable name and then assigning different values to the list in a square bracket. The list is ordered, changeable, and allows duplicate values. For example,

list1 = ["Ram", "Arun", "Kiran"] list2 = [16, 78, 32, 67] list3 = ["apple", "mango", 16, "cherry", 3.4]

Let us look at the below Python examples one by one to find the largest item in a list of comparable elements using the following methods-

  1. Using built-in max() function
  2. Brute Force Approach
  3. Using reduce() function
  4. By implementing the Heap Queue algorithm
  5. Using sort() function
  6. Using sorted() function
  7. By Tail Recursive algorithm
Читайте также:  Check if element is checked javascript

Example: Find the maximum value using max() Function

This is the simplest and straightforward approach to find the largest element. The Python max() function returns the largest item in an iterable. It can also be used to find the maximum value between two or more parameters.

The below example uses an input list and passes the list to max function as an argument.

list1 = [3, 2, 8, 5, 10, 6] max_number = max(list1); print("The largest number is:", max_number)

If the items in the list are strings, first they are ordered alphabetically and then the largest string is returned.

string = ["Find", "maximum", "string", "from", "list"] max_string = max(string, key=len) print("The largest string is:", max_string)

The largest string is: maximum

Example: Find the maximum value using Brute Force Approach

This is the simplest implementation but a bit slower than the max() function because we use this algorithm in a loop.

def large(arr): #root element varible max_ = arr[0] for ele in arr: if(ele > max_): max_ = ele return max_ list1 = [1,4,5,2,6] result = large(list1) print(result)

The above example has defined a function large() to find maximum value and it takes the input list as the argument. In this approach, a variable is used initially to store the first element of the list. Under for loop, each element is compared with this root element variable. If the element is greater than the root element, we assign the value of this item to the root element variable, and at last, after comparing we get the largest element.

Example: Find maximum value using reduce() function

In functional languages, reduce() is an important function and is very useful. In Python 3 reduce() function is moved to a separate module in the standard library called functools . This decision was made to encourage developers to use loops, as they are more readable. Lets us see the below example to use reduce() in two different ways in this case:

The reduce() takes two parameters. The first is the keyword max which finds the maximum number and the second argument is iterable.

from functools import reduce list1 = [-1, 3, 7, 99, 0] print(reduce(max, list1))

The second solution shows an interesting construct using lambda function. The reduce() takes the lambda function as an argument and the lambda() function takes two arguments. It takes a condition and input list to check for maximum value.

from functools import reduce list1 = [-1, 3, 7, 99, 0] print(reduce(lambda x, y: x if x > y else y,list1))

Example: Find maximum value by using the Heap Queue

This module provides an implementation of a heap queue algorithm known as heapq . Heapq is a very useful module for implementing a minimum queue. The important property of the heap is that its smallest element is always the root element. Using the given example, we use heapq.nlargest() function to find the maximum value.

import heapq list1 = [-1, 3, 7, 99, 0] print(heapq.nlargest(1, list1))

The above example, imports heapq module and takes an input list. The function takes n=1 as the first argument because we need to find one maximum value and the second argument is our input list.

Example: Find maximum value using sort() Function

This method uses the sort() function to find the largest element. It takes a list of values as input then sorts the list in ascending order and prints the last element in the list. The last element in the list is list[-1] .

#input list list1 = [10, 20, 4, 45, 99] # sorting the list list1.sort() # print last element print("Largest element is:", list1[-1])

Example: Find maximum value using sorted() Function

This method uses sorted() function to find the largest element. It takes a list of values as an input. Then, the sorted() function sorts the list in ascending order and print the largest number.

list1=[1,4,22,41,5,2] sorted_list = sorted(list1) result = sorted_list[-1] print(result)

Example: Find the maximum value using Tail Recursive Algorithm

This method is not handy and sometimes programmers find it useless. This solution uses iterative recursion, and its working is highly over complicated. It is also a very slow and memory-consuming program. This is because unlike pure functional languages, Python doesn’t optimize for tail recursion, so every call to max() is being held on the stack.

def func(arr, max_=None): if(max_ is None): max_ = arr.pop() current = arr.pop() if(current > max_): max_ = current if(arr): return func(arr, max_) return max_ list1=[1,2,3,4,2] result = func(list1) print(result)

Conclusion

In this article, we learned to find the maximum value from the given input list by using several built-in functions such as max() , sort() , reduce() , sorted() and other algorithms as well. We used some custom codes to understand the brute approach, tail recursion method, and heap algorithm. The tail-recursive algorithm is not generally in use or practice but for different implementation checks, you can read further about it.

Источник

Find Max And Min In A List Python

Working with lists is very common in Python and even more common is to find max and min in a list Python. We will see 3 different methods for each to find min and max in a python list.

A list in python is a collection of user-stored data in order. In a list, data can be of any type like string, integer, float, boolean, etc.

A list can be created by using square brackets [ ] . Example [1, «a», True]

A list can have mixed data or can have only one data type. To find max and min in a list, we will work on a list of numbers. A list that has only integers or float values both negative and positive can be used to find max and min.

find max and min in a list python

Find Maximum Value In List

To find maximum value in a list we will use 3 different methods.

  1. Using max() function
  2. Finding the maximum value using for loop
  3. Using sort() function

1. Using max() function

The max() function is built-in function in Python. It returns the maximum value in a list. It takes a list as an argument and returns the maximum value in the list.

The function accepts the list as an argument. Here is the syntax:

Let’s see an example to find the maximum value in a list.

num = [4, 6, 1, 3, 9, 2] # Find the maximum value in the list print(max(num))

The max() function can also be used to find the maximum value in a list of strings.

To compare the values among strings, the max() function uses their ASCII values. For example, the ASCII value of a is 97 and the ASCII value of z is 122.

str = ["a", "b", "c", "d", "e"] print(max(str))

In the above example, max of the list is e because the ASCII value of e is 101 which is the highest in the list.

Note : max() function does not work on lists of mixed data types.

2. Finding the maximum value using for loop

You can create your own Python function to find the maximum value in a list using for loop and if condition.

Algorithm to find the maximum value in a list

  1. Create a variable max and assign it to the first element of the list
  2. Create a for loop to iterate over the list
  3. Check if the current element is greater than max , if yes then assign it to max . Now current element will become the new max .
  4. Keep iterating over the list until the end of the list and return max .

The example below is implemented using the above algorithm.

def max_value(list): # set first element as max max = list[0] for i in list: # check if the current element is greater than max if i > max: max = i return max num = [12, 65, 54, 39, 102, 37, 72, 33, 5, -28, 0, 15] print(max_value(num))

The above example will find the maximum value in the list and print it.

3. Using sort() function: find max

The sort() function is another built-in function in python using which we can find the maximum value in a list. The sort() function sorts the list in ascending order, which means smallest stays at the first position and largest stays at the last position.

The sort() function takes a list as an argument. TO get the maximum value in a list, you can sort the list and picks the last element of the list.

num = [12, 65, 54, 39, 102, 37, 72, 33, 5, -28, 0, 15] # sort the list num.sort() max = num[-1] print(max)

The above example sorts the list and then picks the last element from the sorted list which is the maximum value in the list.

Find Minimum Value In List

Again to find the minimum from a list we can use similar 3 methods but this time just to find the minimum value.

  1. Using min() function
  2. Finding the minimum value using for loop
  3. Using sort() function

1. Using min() function

The min() function in python finds the minimum value from a list and returns it. It can work with both numbers and strings as well but not with mixed data types.

In the following example, the min() function finds the minimum value in a list of numbers and prints the output.

num = [4, 6.4, 1, -3, 0, 2.5] # Find the minimum value in the list print(min(num))

The min() function can also find the minimum value in a list of strings by comparing their ASCII values.

2. Finding the minimum value using for loop

Creating own function to find minimum value in a list by comparing one value to each other.

Algorithm to find the minimum value in a list

  1. Store the first element of the list in a variable min
  2. Now loop through the list element and compare elements from each other. If the current element is less than min , then assign it to min . Now you have the new min value.
  3. Keep repeating the above steps until the end of the list. At the last min variable will have the actual minimum value of the string.
  4. Return min .

Here is the implementation of the above algorithm.

def min_value(list): # set first element as min min = list[0] for i in list: # check if the current element is less than min if i < min: min = i return min num = [12, 65, 54, 39, 102, 37, 72, 33, 5, -28, 0, 15] print(min_value(num))

The function will find the minimum value in the list and returns it as output.

3. Using sort() function : find min

We can again use the sort() function here to sort the elements of a list in ascending order and then picks the first element of the list which is the minimum value.

num = [12, 65, 54, 39, 102, 37, 72, 33, 5, -28, 0, 15] min = num[0] print(min)

The sort() method sorted the element in ascending order which puts the smallest value in the list at the first position which is -28.

Conclusions

In this short guide, we have covered 3 methods for each to find max and min in a list python. We have also covered the min(), max() and sort() as in-built functions in python and also created a custom function to find minimum and maximum.

Источник

Оцените статью