Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Get Minimum and Maximum from a List
Python lists are mutable, ordered collections that can store multiple elements. Finding the minimum and maximum values from a list is a common operation with several approaches available.
Finding Minimum Value from List
Using min() Function
The min() function returns the smallest element from a list or any iterable. It works with both numbers and strings ?
numbers = [15, 58, 30, 97]
minimum = min(numbers)
print("The smallest element is:", minimum)
The smallest element is: 15
For strings, min() returns the lexicographically smallest value ?
names = ["alina", "misti", "pallvi"]
minimum = min(names)
print("The smallest element is:", minimum)
The smallest element is: alina
Using for Loop
You can iterate through the list and compare each element to find the minimum ?
numbers = [12, 78, 89, 76, 32]
minimum = numbers[0]
for i in numbers:
if i < minimum:
minimum = i
print("The smallest element is:", minimum)
The smallest element is: 12
Using sort() Function
Sort the list in ascending order and access the first element ?
numbers = [56, 78, 90, 67]
numbers.sort()
print("Sorted list:", numbers)
print("Minimum element:", numbers[0])
Sorted list: [56, 67, 78, 90] Minimum element: 56
Finding Maximum Value from List
Using max() Function
The max() function returns the largest element from a list ?
numbers = [15, 58, 30, 97]
maximum = max(numbers)
print("The largest element is:", maximum)
The largest element is: 97
For strings, it returns the lexicographically largest value ?
names = ["krishna", "asif", "david", "yash"]
maximum = max(names)
print("The largest element is:", maximum)
The largest element is: yash
Using for Loop
Iterate through the list and track the largest value encountered ?
numbers = [12, 78, 89, 76, 32]
maximum = numbers[0]
for i in numbers:
if i > maximum:
maximum = i
print("The largest element is:", maximum)
The largest element is: 89
Using sort() Function
Sort the list and access the last element using index -1 ?
numbers = [67, 89, 9, 76]
numbers.sort()
print("Largest element is:", numbers[-1])
Largest element is: 89
Comparison of Methods
| Method | Time Complexity | Modifies Original List? | Best For |
|---|---|---|---|
min()/max() |
O(n) | No | Simple, readable code |
| For loop | O(n) | No | Custom comparison logic |
sort() |
O(n log n) | Yes | When you need sorted list |
Conclusion
Use min() and max() functions for the most efficient and readable approach. The for loop method is useful when you need custom comparison logic, while sort() is best when you also need the sorted list.
