Python max() and min() – finding max and min in list or array

Python examples to find the largest (or the smallest) item in a collection (e.g. list, set or array) of comparable elements using max() and min() methods.

1. Python max() function

max() function is used to –

  1. Compute the maximum of the values passed in its argument.
  2. Lexicographically largest value if strings are passed as arguments.

1.1. Find largest integer in array

>>> nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]

>>> max( nums )

42		#Max value in array

1.2. Find largest string in array

>>> blogName = ["how","to","do","in","java"]

>>> max( blogName )

'to'		#Largest value in array

1.3. Find max key or value

A little complex structure.

>>> prices = {
   'how': 45.23,
   'to': 612.78,
   'do': 205.55,
   'in': 37.20,
   'java': 10.75
}

>>> max( prices.values() )
612.78

>>> max( prices.keys() ) 	#or max( prices ). Default is keys().
'to'

2. Python min() function

This function is used to –

  1. compute the minimum of the values passed in its argument.
  2. lexicographically smallest value if strings are passed as arguments.

2.1. Find lowest integer in array

>>> nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]

>>> min( nums )

-4		#Min value in array

2.2. Find smallest string in array

>>> blogName = ["how","to","do","in","java"]

>>> min( blogName )

'do'		#Smallest value in array

2.3. Find min key or value

A little complex structure.

>>> prices = {
   'how': 45.23,
   'to': 612.78,
   'do': 205.55,
   'in': 37.20,
   'java': 10.75
}

>>> min( prices.values() )
10.75

>>> min( prices.keys() ) 	#or min( prices ). Default is keys().
'do'

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.