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 –
- Compute the maximum of the values passed in its argument.
- 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 –
- compute the minimum of the values passed in its argument.
- 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 !!
Leave a Reply