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
Finding the Maximum and Minimum in a Python set
Python sets store unique elements in an unordered collection. To find the maximum and minimum values in a set, Python provides several approaches using built-in functions like max(), min(), and sorted().
Using Built-in max() and min() Functions
The most direct approach is to apply max() and min() functions directly to the set ?
# Define a set with integer values
numbers = {5, 2, 8, 1, 9, 18}
# Find maximum and minimum values directly
maximum = max(numbers)
minimum = min(numbers)
print("Maximum:", maximum)
print("Minimum:", minimum)
Maximum: 18 Minimum: 1
This is the most efficient method as it works directly on the set without any conversion.
Using sorted() Function
The sorted() function converts the set to a sorted list, allowing us to access the first (minimum) and last (maximum) elements ?
# Create a set
numbers = {5, 2, 8, 1, 9, 18}
# Sort the set elements
sorted_numbers = sorted(numbers)
# Get min and max from sorted list
minimum = sorted_numbers[0]
maximum = sorted_numbers[-1]
print("Sorted list:", sorted_numbers)
print("Minimum:", minimum)
print("Maximum:", maximum)
Sorted list: [1, 2, 5, 8, 9, 18] Minimum: 1 Maximum: 18
Converting Set to List
You can convert the set to a list first, then apply max() and min() functions ?
# Initialize the set
numbers = {5, 2, 8, 1, 9, 18}
# Convert set to list
numbers_list = list(numbers)
# Find maximum and minimum
maximum = max(numbers_list)
minimum = min(numbers_list)
print("List:", numbers_list)
print("Maximum:", maximum)
print("Minimum:", minimum)
List: [1, 2, 5, 8, 9, 18] Maximum: 18 Minimum: 1
Comparison
| Method | Time Complexity | Memory Usage | Best For |
|---|---|---|---|
max()/min() directly |
O(n) | Low | Simple min/max lookup |
sorted() |
O(n log n) | High | When you need sorted data |
| Convert to list | O(n) | Medium | Further list operations needed |
Working with Different Data Types
These methods work with various data types that support comparison ?
# Set of strings
fruits = {'apple', 'banana', 'cherry', 'date'}
print("Fruits - Min:", min(fruits), "Max:", max(fruits))
# Set of floats
prices = {10.5, 25.99, 5.0, 100.25}
print("Prices - Min:", min(prices), "Max:", max(prices))
Fruits - Min: apple Max: date Prices - Min: 5.0 Max: 100.25
Conclusion
Use max() and min() directly on sets for the most efficient approach. Use sorted() when you need the complete sorted sequence along with min/max values.
