Python min() Built in Function
The min() function in Python returns the smallest item in an iterable or the smallest item among two or more arguments. An iterable can be a list, tuple, set, dictionary, string, etc. The min() function can also take a key function to customize the comparison criteria.
Here are some examples of using min() function in Python:
Using min() with a single iterable
# This example returns the smallest number in a list
numbers = [9 ,34 ,11 ,-4 ,27]
smallest = min(numbers)
print(smallest)
# Output: -4
Using min() with multiple arguments
# This example returns the smallest number among four arguments
result = min(5 ,10 ,25 ,99)
print(result)
# Output: 5
Using min() with strings
# This example returns the alphabetically first string in a list
words = ["apple" ,"banana" ,"cherry" ,"date"]
first = min(words)
print(first)
# Output: apple
Using min() with a key function
# This example returns the shortest string in a list using len() as a key function
words = ["hello" ,"world" ,"welcome" ,"to" ,"Python"]
shortest = min(words ,key=len)
print(shortest)
# Output: to
Using min() with dictionaries
# This example returns the key with the lowest value in a dictionary
scores = {"Alice": 90 ,"Bob": 85 ,"Charlie": 95}
lowest = min(scores ,key=scores.get)
print(lowest)
# Output: Bob
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment